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

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

问题描述

在我们的项目中成功使用Entity Frameworks进行了迁移. 但是现在我遇到了一种特殊情况,在这种情况下,我需要更新需要一些业务逻辑的表(作为C#代码位于我们的应用程序中).因此,我尝试在migrations 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. 通常在以下情况下执行自定义代码是否是一种好习惯? DBmigrations?
  2. 如果没有,我该如何满足我执行自定义代码的需要 案子? (无需在存储过程中重写业务逻辑或 有点)
  3. 如果是,我在做什么错?如何在迁移中执行此代码而又不阻止它?
  1. Is it good practise in general to execute custom code in DBmigrations?
  2. If not, how can I accomplish the need of custom code execution in my case? (without rewriting the business logic in a stored procedure or somewhat)
  3. If yes, what I am doing wrong? How can I execute this code within an migration and without blocking it?

推荐答案

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. 在迁移配置类(通常是Migrations \ Configuration.cs)的Seed方法中执行逻辑.在Update-Database期间应用了所有迁移之后,将调用此方法

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

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