OnModelCreating和非自动迁移有何关系? [英] How do OnModelCreating and non automatic Migrations relate?

查看:89
本文介绍了OnModelCreating和非自动迁移有何关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我添加一个与数据库有某些关系的新表,然后运行 Add-Migration 时,我看到在 Up中生成了代码方法添加表及其关系。
但是,我更喜欢在 OnModelCreating 方法中使用流畅的API定义关系。这两种方法如何相互作用?我可以从定义实例关系的 Up 方法中删除代码吗?

When I add a new table that has some relations to my database and then run Add-Migration I see that code is generated in the Up method to add the table and its relations. However, I prefer to define the relation using the fluent API in the OnModelCreating method. How do these two methods interact? Can I delete the code from the Up method that defines the relation for instance?

推荐答案

每个对象的用途完全不同:

Each of them has completely different purpose:


  • OnModelCreating 用于模型的内联fluent-API定义。这些定义以及默认约定,数据注释和配置类构成了模型的完整定义。

  • 显式迁移定义了必须执行的操作,以便将数据库迁移到当前所需的格式模型

  • OnModelCreating is used for inline fluent-API definitions of your model. These definitions together with default conventions, data annotations and configuration classes forms the complete definition of the model.
  • Explicit migration defines what must be done to database to migrate it to the form required by your current model

现在,这两个之间的关系如何?迁移具有两个用于生成迁移代码的输入( Up Down 方法)。一个输入是存储在数据库的 __ MigrationHistory 表中的最后一个迁移记录。该记录包含代表数据库的序列化模型。此输入是可选的,因为第一次迁移必须在没有它的情况下进行。第二个输入是强制性的-通过执行当前程序集中的代码来检索当前模型=> Add-Migration 将执行您的 OnModelCreating 获取当前模型并将其与从数据库中检索到的模型进行比较。比较的结果是显式迁移中 Up Down 方法的内容。

Now, how those two relate? Migration has two inputs which are used to generate migration code (Up and Down methods). One input is the last migration record stored in __MigrationHistory table in the database. This record contains serialized model representing the database. This input is optional because first migration must work without it. The second input is mandatory - it is your current model which is retrieved by executing the code in your current assembly => Add-Migration will execute your OnModelCreating to get the current model and compare it with the model retrieved from the database. The result of comparison is content of Up and Down methods in the explicit migration.

这篇关于OnModelCreating和非自动迁移有何关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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