Search code examples
c#entity-frameworkasp.net-coreef-code-firstef-core-2.1

When does EFCore OnModelCreating get invoked?


I know it gets called when you create Migrations, but is that the ONLY time it's called?

It seems unlike that it is called when a request comes in (in the context of a WebApi system), but does it get called on server startup? Or during the deployment process at any point? Or during Migration running?

Asking for data-seeding purposes, though I'd like to know the answer in the abstract too.


Solution

  • At a minimum, the method is also called when applying Migrations, which is often configured to be automatically done on WebHost Startup. At a guess, this is because EF attempts to validate the Database state, before performing migrations. That validation appears to demand a model for comparison, thus the method is run.

    There may be other occassions on which it runs.