What is the relationship between OnModelCreating and non automatic Migrations?

When I add a new table that has some relationships with my database and then starts Add-Migration , I see that the code is generated in the Up method to add the table and its relationships. However, I prefer to define the relationship using the free API in the OnModelCreating method. How do these two methods interact? Is it possible to remove code from the Up method, which defines the relation for an example?

+6
source share
1 answer

Each of them has a completely different purpose:

  • OnModelCreating used for the built-in Fluent-API definitions of your model. These definitions, together with the default conventions, data annotations, and configuration classes, form the complete definition of the model.
  • Explicit migration determines what needs to be done for the database in order to transfer it to the form needed by your current model.

Now, how are these two connected? Migration has two inputs that are used to generate the migration code ( Up and Down methods). One entry is the last migration entry stored in the __MigrationHistory table in the database. This entry contains a serialized model representing the database. This input is optional because the first migration should work without it. The second input is required - your current model, obtained 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 obtained from the database. The result of the comparison is the content of the Up and Down methods in explicit migration.

+11
source

Source: https://habr.com/ru/post/918872/


All Articles