7

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.

2
  • 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. Commented Jan 10, 2012 at 19:51
  • Is this related question of any help? stackoverflow.com/questions/4845246/…
    – The Nail
    Commented Jan 10, 2012 at 19:56

2 Answers 2

14

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
  • 1
    you answer is so useful for me. Commented Jan 10, 2012 at 20:02
  • I got the following error: ExecuteNonQuery requires an open and available Connection. The connection's current state is closed.
    – Icerman
    Commented Oct 28, 2014 at 19:03
2

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
  • Will changes to a stored procedure created in this way be tracked by migrations?
    – Craig
    Commented Dec 3, 2021 at 15:38
  • @Craig, I would think so. I did not test it. Commented Jan 11, 2022 at 23:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.