Entity Framework throws a model compatibility exception.

code-first entity-framework

Question

This issue occurs when I run my web application and attempt to store data into a database:

Model compatibility cannot be checked because the database does not contain model metadata. Model compatibility can only be checked for databases created using Code First or Code First Migrations.

I've tried several things to address this issue, but it still exists.

1
3
5/17/2012 11:07:49 AM

Accepted Answer

When creating locally, there is really no need to use migrations. Setting the database Initializer to always delete the database, then executing some code that communicates with the database, will cause the database to be restored and the error to disappear.

That's how I do it, so it should work.

3
5/17/2012 11:11:28 AM

Popular Answer

Manually remove the database, restart the project with:

public class DbDataContext : DbContext
{
    public IDbSet<FlightType> FlightTypes { get; set; }

    public DbDataContext()
    {
        //Validates if database Exists or if is CompatibleWithModel
        //Using when Databes is productive - use code first migrations for db changes in this case
        //Database.SetInitializer(new ValidateDatabase<DbDataContext>());

        //Custom Initializer - crates databse with required entries
        //Using while developing
        Database.SetInitializer<DbDataContext>(new DatabaseInitializer<DbDataContext>());
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }
}

DatabaseInitializer:

public class DatabaseInitializer<T> : DropCreateDatabaseIfModelChanges<DbDataContext>
{
    protected override void Seed(DbDataContext dbDataContext)
    {
        dbDataContext.FlightTypes.Add(new FlightType { FlightTypeNummer = "axd", Name = "AXD_LX", IsDefault = true });

        base.Seed(dbDataContext);
     }
 }

ValidateDatabase:

public class ValidateDatabase<TContext> : IDatabaseInitializer<TContext> where TContext : DbContext
{
    public void InitializeDatabase(TContext context)
    {
        if (!context.Database.Exists())
        {
            throw new InvalidOperationException("Database does not exist");
        }
        if (!context.Database.CompatibleWithModel(true))
        {
            throw new InvalidOperationException("The database is not compatible with the entity model.");
        }
    }
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow