Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I define a stored procedure in Entity Framework (code first)?

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.

like image 440
Mahdi jokar Avatar asked Jan 10 '12 19:01

Mahdi jokar


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

  • MSDN - DbCommand Class
like image 66
dknaack Avatar answered Nov 22 '22 05:11

dknaack


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);
    }
}
like image 24
Kevin Swarts Avatar answered Nov 22 '22 07:11

Kevin Swarts