How do OnModelCreating and non automatic Migration

2019-03-27 17:48发布

问题:

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.