Model compatibility exception in Entity Framework

When I run my web application and try to save data in a databse, this exception occurs:

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

I am trying to solve a problem, but that is not all!

+3
source share
3 answers

, . , , , , , , .

, .

+3

,

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.");
        }
    }
}
+2

-? , ?

PM> Enable-Migrations
0

All Articles