实体框架在迁移之前执行SQL [英] entity framework execute SQL before migrations

查看:122
本文介绍了实体框架在迁移之前执行SQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个使用实体框架6的现有项目,并以代码优先。我需要在迁移之前运行一些SQL。



我有一个带有种子方​​法的DbMigrationsConfiguration类,但种子在迁移后运行。



我认为如果我在构造函数中运行我的SQL,但是我无法获得对上下文的引用,那么它将会起作用。



有没有人知道如何做?

解决方案

您可以在所需的迁移类中使用Sql方法。

  public partial class OneOfYourMigrations:DbMigration 
{
public override void Up()
{
// EF生成的迁移代码如
// CreateTable或AddColumn等...
//现在运行您的自定义sql - 在这里我正在更新现有列
Sql(UPDATE dbo.YourTable SET Column1 ='VALUE1');
}

public override void Down()
{
// EF生成的代码回滚
}
}

所以步骤是:




  • 使用Add-Migration生成迁移类

  • 使用与上述相似的代码更改类

  • 使用Update-Database
  • $运行迁移b $ b

I am working on an existing project that uses Entity-Framework 6 with code-first. I have a need to run some SQL before the migrations run.

I have a DbMigrationsConfiguration class with a seed method, but seed runs after the migrations.

I think it will work if I run my SQL in the constructor but I can't get a reference to the context.

Does anyone know how to do this?

解决方案

You could use the 'Sql' method within the desired migration class.

public partial class OneOfYourMigrations : DbMigration 
{ 
    public override void Up() 
    { 
        //EF generated migration code here such as
        //CreateTable or AddColumn etc...
        //Now run your custom sql - here I'm doing an update to an existing column
        Sql("UPDATE dbo.YourTable SET Column1 = 'VALUE1' "); 
    } 

    public override void Down() 
    { 
        //EF generated code to rollback
    } 
}     

So the steps are;

  • Generate migration class using Add-Migration
  • Alter the class using code similar to above
  • Run the migration using Update-Database

这篇关于实体框架在迁移之前执行SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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