I am trying to use EF 4 Code First pattern. My initialization code is as follows:
Create Model Builder:
private static DbModelBuilder CreateModelBuild()
{
var builder = new DbModelBuilder();
//add entity classes about 12 of them
builder.Conventions.Remove<IncludeMetadataConvention>();
return builder;
}
Create session:
private bool BuildSqlServerSession(DbModelBuilder builder)
{
var model =
builder.Build(new SqlConnection(@"connection string"));
var cm = model.Compile();
var context = new LittlePOSContext(cm);
var dbExists = context.Database.Exists();
_session = new EFSession(context);
return dbExists;
}
This works when I run the code for first time. But when running on second time and trying to add an object using context.Add(myEntity)
I get following exception:
Model compatibility cannot be checked because the EdmMetadata type was not
included in the model. Ensure that IncludeMetadataConvention has been added
to the DbModelBuilder conventions.
I have tried removing following line:
builder.Conventions.Remove<IncludeMetadataConvention>();
but I still get the error.
Well it feels somewhat silly but the real culprit was following statement:
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<MyContext>());
It seems that DropCreateDatabaseIfModelChanges
is not compatible with Code First
approach or it is some other mystery that I don't understand (yet).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With