EF 6代码优先,具有自定义存储过程 [英] EF 6 code-first with custom stored procedure

查看:78
本文介绍了EF 6代码优先,具有自定义存储过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用代码优先"方法创建MVC 5应用程序,但是我还在SQL Server数据库上创建了一些存储过程,有没有一种方法可以在创建数据库时也在c#中生成这些存储过程,也许通过执行sql脚本,如果可以的话,该在哪里做?

I´m creating a MVC 5 app with a Code-First approach, but I also created some stored procedures on the SQL Server database, is there a way to also generate these stored procedures in c# when the database is created, maybe by executing a sql script, if so where should I do this?

推荐答案

我将使用代码迁移.

在您的Nuget软件包管理器中,您可以通过键入以下内容来设置空白迁移

From your Nuget Package Manager you can set up a blank migration by typing

add-migration AddMyStoredProcedure

这应该会生成一个空的类,

This should generate an empty class like so

public partial class AddMyStoredProcedure : DbMigration
{
    public override void Up()
    {
    }

    public override void Down()
    {
    }
}

您需要做的就是像这样添加存储过程(请记住在Down方法中删除该存储过程,以防将来需要回滚迁移时使用该存储过程.

All you need to do is add your stored procedure like so (remember to drop the stored procedure in the Down method in case you need to roll back the migration in the future).

    public partial class AddMyStoredProcedure : DbMigration
{
    public override void Up()
    {
        Sql(@"
            CREATE PROCEDURE dbo.GetMyAddress
            AS
            SELECT * FROM Person.Address");
    }

    public override void Down()
    {
        Sql("DROP PROCEDURE dbo.GetMyAddress");
    }
}

最后更新您的数据库

update-database

这篇关于EF 6代码优先,具有自定义存储过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆