Entity Framework Core OnModelCreating vs Migration, the correct development workflow

asp.net-core c# entity-framework-core

Question

can you please explain to me the difference between having the following:

  • Decorate a class with EF Core attribute such as DataAnnotations VS using the code inside OnModelCreating to define relationships and mapping?
  • Creating a Migration class using dotnet ef migrations add "xyz" VS configuring it into OnModelCreating?

I am trying to make a sort of "Development workflow" but the docs are not really clear about it.

I found that I should:

  1. Create your first "Database Context"
  2. Create a set of classes representing my Model
  3. Override OnModelCreating to specify the mapping strategies for each Model object
  4. Execute add migrations and ef update as many times as I change something

Is this the correct flow to work with Entity Framework Core?

1
2
3/6/2017 9:23:30 PM

Accepted Answer

Decorate a class with EF Core attribute such as DataAnnotations VS using the code inside OnModelCreating to define relationships and mapping?

Data Annotations are 'inline', but you mix entities with persistence logic. It's the sweet spot, in my opinion. OnModelCreating enables you to use the 'Fluent API', which is more powerful and flexible, but/and detaches the persistence logic somewhat from your entities. Sometimes you use a mix of both - data annotations and Fluent API.

Creating a Migration class using dotnet ef migrations add "xyz" VS configuring it into OnModelCreating?

Not sure I understand this. I don't see an alternative to migrations.

The way I work with EF (code-first) is:

  1. I write my entities and add data annotations to them
  2. I generate a migration and get SQL script from it, then delete the migration code
  3. Execute the .SQL against the database
  4. Run the code
  5. Entity changes
  6. Generate new migration .SQL and store it as part of the project

Basically a 'migration' is necessary when you want to update the database to be compatible with your new/changed code.

OnModelCreating is necessary when you have to tell EF how the entities map to a database. You shouldn't confuse the two things.

6
3/6/2017 2:25:45 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow