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.
Brandon Roberson May 31 '11 at 12:35 a.m. 2011-05-31 00:35
source share