J
J
JoraInTheSky2017-09-19 15:30:58
C++ / C#
JoraInTheSky, 2017-09-19 15:30:58

Stored procedure from c# code in EF(Code First)?

There is a data context and a data initializer,

public class ShoopProductContext: DbContext
    {
        
        public DbSet<Client> Clients { get; set; }

        public DbSet<OrderLine> OrderLines { get; set; }

        public DbSet<Order> Orders { get; set; }

        public DbSet<Product> Products { get; set; }
    }

    public class shoopProductsInitializer : DropCreateDatabaseAlways<ShoopProductContext>
    {
        protected override void Seed(ShoopProductContext context)
        {
            context.Products.Add(new Product { NameProduct = "11" });//Тут должна быть ХП
            context.SaveChanges();// 
        }
    }

it is necessary to fill the table with the data through , in the data initializer. I have questions
  1. How to create HP in c# code in EF(Code first)?
  2. Is it possible to add HP to the database with the Code first approach in the data initializer?
  3. How to run it (XP) from the code (C #)?
  4. Is it possible to create a trigger in this HP and bind it to a table?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
MrDywar Pichugin, 2017-09-19
@Dywar

Stored Procedure in Entity Framework
Stored Procedures Stored procedures
can be created by migration, and it will be 100% on every database.
I think everything can be done in storage, the main thing is to return a normal object.

M
Maxmyd, 2017-09-20
@Maxmyd

1 and 2 - register in migration

protected override void Up(MigrationBuilder migrationBuilder)
{
  migrationBuilder.Sql(@"CREATE PROC dbo.Execute ...");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
  migrationBuilder.Sql(@"DROP PROC dbo.Execute");
}

3. In your context, prescribe and call
public class MyDbContext: DbContext
{
public IEnumerable<TEntity> ExecuteSql<TEntity>(string query, dynamic parameters = null, CommandType commandType = CommandType.Text)
        {
            using (SqlConnection connection = new SqlConnection(Database.GetDbConnection().ConnectionString))
            {
                connection.Open();
                return connection.Query<TEntity>(query, (object)parameters, commandType: commandType);
            }
        }
}

4. You can, it's also T-SQL

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question