Entity Framework throws a model compatibility exception.

code-first entity-framework

Question

When I execute my web app and try to save data into databse, this exception happens :

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 try lot of issue for resolve this problem , but it persist yet !!

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

Accepted Answer

Using migrations isn't really necessary if you're developing on your local machine. You can just set the database Initializer to drop the database always, run some code that interacts with the database, and then you'll see that the database will be recreated and the error will be gone.

Should work, that's how I do it.

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

Popular Answer

delete the database manually, then 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