EF 4.1 Code First - OnModel Create Call Time

When I debug the application, this method does not seem to execute in the context of the DbContext constructor. So when is it called then?

+8
entity-framework ef-code-first
Apr 12 '11 at 11:20
source share
3 answers

This method is called when EF needs to access the database for the first time (so this is not during context instancing). If the database does not exist, it uses the information from the compiled model to create it. A model is created only once for each application (it is cached internally), so even if you place the context, your model will still be reused for the next instance.

+8
Apr 12 '11 at 18:29
source share

To be clear, OnModelCreating has nothing to do with whether EF creates a database for you.

To interact with the database, the Entity Framework must create a model of the objects that will be stored. If it is not already built and cached, this event fires.

After the model is built, a hash is generated from it, and EF then tries to connect to the database to see if it exists (a), (b) contains version information, the previous hash stored in the EdmMetadata table, and (c ) whether this hash matches the previously calculated from the model.

If the hashes do not match, EF uses the database initializer that was installed (by calling Database.SetInitializer(new SomeInitializerType() ), which may or may not be reset, create or otherwise modify your database. The default initializer used, when you do not specify another, it does nothing for your database, and once it is started, the Entity Framework will refuse to interact with the database if it is not synchronized.

If your database does not contain an EdmMetadata table with a hash in it, the Entity Framework assumes that you manage the database schema yourself and, fortunately, try to use it, hoping that you will succeed. If the scheme does not meet EF expectations later in the future, you will get errors when calling SaveChanges (), etc.

In all of these scenarios, whether you are managing your own database schema or allowing EF to drop and recreate it as needed, whether the database is synchronized with your model or not, the OnModelCreating event is fired for the first time Entity Framework is required to know that it is saved.

+30
May 31 '11 at a.m.
source share

OnModel Creates triggers when EF4 creates a database. Usually this event is used to configure the way the EF4 database was created, so if you run your application earlier and your model remains the same, the database already exists and EF4 does not try to create a new one (although this behavior also depends on some configuration parameters).

-2
Apr 12 2018-11-11T00:
source share



All Articles