I define my model in Entity Framework (code first), but how can I define a stored procedure in my model? I want to create my model and have it generate the stored procedure in my database when my database is generated from my model.
There is no built in direct mapping support for stored procedures in Entity Framework code first at the moment. But you can exec any sql query (create your stored procedure) like in my sample.
public class MyDatabaseContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
DbCommand cmd = Database.Connection.CreateCommand();
cmd.CommandText = "create stored procedure ....";
cmd.ExecuteNonQuery();
}
}
I'm using Entity Framework 6 so things may have changed. The database is not created in OnModelCreating, but it did work in the DbInitializer like this...
public class MyDbInitializer : DropCreateDatabaseIfModelChanges<MyDbContext> {
protected override void Seed(MyDbContext context) {
string sql = @"CREATE PROCEDURE...";
context.Database.ExecuteSqlCommand(sql);
base.Seed(context);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With