How do OnModelCreating and non automatic Migrations relate?

孤人 提交于 2019-12-04 11:20:17

问题


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?


回答1:


Each of them has completely different purpose:

  • 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

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.



来源:https://stackoverflow.com/questions/11177380/how-do-onmodelcreating-and-non-automatic-migrations-relate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!