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
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.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With