EF 迁移中的自定义代码执行 [英] Custom code execution in EF migrations

查看:27
本文介绍了EF 迁移中的自定义代码执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的项目中成功使用实体框架迁移.但是现在我遇到了一个特殊情况,我需要更新需要一些业务逻辑的表(位于我们的应用程序中作为 C# 代码).因此,我尝试在迁移 Up 方法中生成一个线程,并使用业务逻辑执行此表更新.应用程序执行不需要此表更新,应在后台进行.

Working with the Entity Frameworks migrations successfully in our project. But now I run into a special case where I need to update a table in need of some business logic (located in our application as C# code). So I tried to spawn a thread in the migrations Up method and doing this table update with the business logic. This table update is not required for the application execution and should be occur in the background.

我这样做有点像这样:

public partial class MyMigration : DbMigration
{
  public override void Up()
  {
     // ... do some sql migration here ...

     // after executing the sql migrations custommethod should run
     // migration seems to wait until CustomMethod finished work
     new Thread(() => ExecuteCustomMethodDatabaseContext()).Start();
  }
}

我希望 Up 方法在启动线程后返回,并且 EF 将 MigrationHistory 中的迁移设置为完成.因此,应用程序可以启动并在后台某处更新表格.

I would expect that the Up method returns after starting the thread and EF sets the migration in the MigrationHistory to done. Thus the app can start and somewhere in the background the table gets updated.

但并非如此,迁移似乎在线程运行时运行(这需要很多时间).

But not so, the migrations seems to run while the thread runs (this takes a LOT of time).

所以我的相应问题:

  1. 在一般情况下执行自定义代码是一种好习惯吗?数据库迁移?
  2. 如果没有,我如何在我的案件?(无需重写存储过程中的业务逻辑或有点)
  3. 如果是,我做错了什么?如何在迁移中执行此代码而不阻塞它?

推荐答案

DbMigration 上的 Up 和 Down 方法只是建立了一个内存模型,该模型稍后会被转换为 SQL.执行自定义逻辑有两种选择:

The Up and Down methods on DbMigration merely build up an in-memory model that later gets translated to SQL. You have two options for executing custom logic:

  1. 使用 Sql 方法使用 T-SQL 在数据库服务器上执行您的逻辑.
  2. 在迁移配置类(通常是 MigrationsConfiguration.cs)的 Seed 方法中执行逻辑.在更新数据库期间应用所有迁移后调用此方法

这篇关于EF 迁移中的自定义代码执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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