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.
-
i want define a model from my Store procedure.and when i use my model for the first time Entity generate my Store procedure in SQL server.– Mahdi jokarCommented Jan 10, 2012 at 19:51
-
Is this related question of any help? stackoverflow.com/questions/4845246/…– The NailCommented Jan 10, 2012 at 19:56
Add a comment
|
2 Answers
Description
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.
Sample
public class MyDatabaseContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
DbCommand cmd = Database.Connection.CreateCommand();
cmd.CommandText = "create stored procedure ....";
cmd.ExecuteNonQuery();
}
}
More Information
-
1
-
I got the following error: ExecuteNonQuery requires an open and available Connection. The connection's current state is closed.– IcermanCommented Oct 28, 2014 at 19:03
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);
}
}
-
Will changes to a stored procedure created in this way be tracked by migrations?– CraigCommented Dec 3, 2021 at 15:38
-