Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
812 views
in Technique[技术] by (71.8m points)

.net - EF 4.1 Code First - OnModelCreating call time

When I debug my application this method seems not to be executing in constructor context of DbContext. So when it is called then?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...