实体框架在迁移前执行 SQL [英] entity framework execute SQL before migrations
本文介绍了实体框架在迁移前执行 SQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在开发一个使用 Entity-Framework 6 和代码优先的现有项目.我需要在迁移运行之前运行一些 SQL.
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.
我有一个带有种子方法的 DbMigrationsConfiguration 类,但种子在迁移之后运行.
I have a DbMigrationsConfiguration class with a seed method, but seed runs after the migrations.
如果我在构造函数中运行我的 SQL 但我无法获得对上下文的引用,我认为它会起作用.
I think it will work if I run my SQL in the constructor but I can't get a reference to the context.
有人知道怎么做吗?
推荐答案
您可以在所需的迁移类中使用Sql"方法.
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
}
}
所以步骤是;
- 使用 Add-Migration 生成迁移类
- 使用与上述类似的代码更改类
- 使用更新数据库运行迁移
这篇关于实体框架在迁移前执行 SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文