Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Model compatibility exception in Entity Framework

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

like image 956
ucef Avatar asked Jul 12 '26 23:07

ucef


2 Answers

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.

like image 54
Leon Cullens Avatar answered Jul 17 '26 19:07

Leon Cullens


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.");
        }
    }
}
like image 41
ping Avatar answered Jul 17 '26 20:07

ping



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!