Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top