How do OnModelCreating and non automatic Migrations relate?
Asked Answered
R

1

10

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?

Roseroseann answered 24/6, 2012 at 12:19 Comment(0)
W
16

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.

Winfield answered 24/6, 2012 at 20:12 Comment(2)
Thanks! So, if I understand correctly the code in the Up method will reflect the definitions set in the OnModelCreating method (supposing that you added a Migration after writing the fluent API definition of course). One must not remove these reflected definitions from Up.Roseroseann
What would be the best way to inject code into the migrations code using OnModelCreating's ModelBuilder? Would that be HasAnnotation?Tithe

© 2022 - 2024 — McMap. All rights reserved.