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 jokar– Mahdi jokar2012-01-10 19:51:11 +00:00Commented Jan 10, 2012 at 19:51
-
Is this related question of any help? stackoverflow.com/questions/4845246/…The Nail– The Nail2012-01-10 19:56:21 +00:00Commented 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
2 Comments
Mahdi jokar
you answer is so useful for me.
Icerman
I got the following error: ExecuteNonQuery requires an open and available Connection. The connection's current state is closed.
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);
}
}
2 Comments
Craig
Will changes to a stored procedure created in this way be tracked by migrations?
Kevin Swarts
@Craig, I would think so. I did not test it.