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

可紊 提交于 2019-12-08 19:08:08

问题


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.


回答1:


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



回答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);
    }
}


来源:https://stackoverflow.com/questions/8809485/how-can-i-define-a-stored-procedure-in-entity-framework-code-first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!