When I debug my application this method seems not to be executing in constructor context of DbContext. So when it is called then?
This method is called when EF needs to access database for the first time (so it is not during context instancing). If the database doesn't exists it uses information from compiled model to create it. The model is created only once per application (it is cached internally) so even if you dispose the context your model will be still reused for the next instance.
To be clear, OnModelCreating has nothing to do with whether or not EF is creating the database for you.
In order to interact with the database, Entity Framework must build up a model of the entities that will be persisted. If it doesn't already have that model built and cached, this event fires.
After the model is built, a hash is generated from it, and EF then attempts to connect to the database to see if (a) it exists, (b) it contains version information, a previous hash stored in the EdmMetadata table, and (c) whether or not that hash matches the one previously calculated from the model.
If the hashes do not match, EF uses the database initializer that's been set (by calling Database.SetInitializer(new SomeInitializerType()
), which may or may not drop, create, or otherwise modify your database. The default initializer, used when you don't specify a different one, does nothing to your database, and once it has run, Entity Framework will refuse to interact with the database if it is out of sync.
If your database does not contain an EdmMetadata table with a hash in it, Entity Framework assumes you're managing the database schema on your own and happily attempts to make use of it, hoping you've gotten things right. If the schema doesn't match EF's expectations later on down the road, you'll get errors when calling SaveChanges() and such.
In all of these scenarios, whether you're managing your own database schema or letting EF drop and recreate it as needed, whether the database is in sync with your model or not, the OnModelCreating event fires the first time Entity Framework needs to know what it's persisting.
OnModelCreating triggers when EF4 is creating the database. Usually this event is used to configure the way EF4 generates the database, so if you executed your application before and your model remains the same, the database is already there and EF4 does not try to generate a new one (although this behaviour also depends on some configuration parameters).