3
votes

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 !!

3

3 Answers

3
votes

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.

2
votes

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.");
        }
    }
}
0
votes

Are you trying to use Code-First Migrations? If so, have you run the following command in the Package Manager Console?

PM> Enable-Migrations