EF Core 6.0 onModelCreating running when running ASP.NET Core Application (outside the Migration)

Viewed 39

I have an application written in ASP.NET Core using .NET 6.0.7. And I have generated migrations and applied them to the database using database-update manually - or for production we are using the ef bundle to update the database.

This being said I am using HasData to seed initial data. This is achieved inside the OnModelCreating method in the DbContext. And whenever any of the seed data changes I cover this with a new migration.

NOTE: I do not have any migration code in the program.cs for the ASP.NET Core Web API code, but it seems that during debugging (and on production), OnModelCreating is still called - WHY?

There should be no reason to run OnModelCreating when in debug or production when starting up the Web API. Is this an error in EF Core? Or am I seriously missing something?

1 Answers

OnModelCreating supposed to run every time, this is normal.

In EF Core, seeding data can be associated with an entity type as part of the model configuration. Then EF Core migrations can automatically compute what insert, update or delete operations need to be applied when upgrading the database to a new version of the model.

You should only use HasData if you want migrations to manage applying changes to it, otherwise just add it to the database using SaveChanges when needed.

For more details, see Creating and configuring a model and Data Seeding.

Related