Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF 4 Code First: Model compatibility cannot be checked because the EdmMetadata type was not included in the model

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.

like image 655
TheVillageIdiot Avatar asked Dec 25 '11 17:12

TheVillageIdiot


1 Answers

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).

like image 189
TheVillageIdiot Avatar answered Oct 17 '22 08:10

TheVillageIdiot