C# – How to Fix ‘The model backing the context has changed since the database was created.’ in database first

asp.netcentity-framework

I am trying to connect entity to an existing database, but am having a hard time figuring out why I am getting the following error:

The model backing the 'RPSContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).

As I mentioned, I am connecting to an existing database. So I don't need entity to modify structure. I'd just like to be able to select/insert/update/etc.

Design:

DB Design

Model:

public class ProductAttributePriceAdjustment
{
        [Key]
        public int AdjustmentId { get; set; }
        public int StoreProductId { get; set; }
        public int StoreId { get; set; }
        public string ProductId { get; set; }
        public int ProductSizeId { get; set; }
        public decimal Adjustment { get; set; }
        public int PointsAdjustment { get; set; }
        public int ProductColorID { get; set; }
}

Context

public class RPSContext : DbContext
{
        public RPSContext() : base("ApplicationConnection")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<ProductAttributePriceAdjustment>().ToTable("ProductAttributePriceAdjustment");
        }

        public DbSet<ProductAttributePriceAdjustment> PriceAdjustments { get; set; }
}

Best Answer

Almost every time I see this error it's because the database schema and the schema the code is expecting is not synced up. At some point the schema changed and you did not reflect your changes in code.

For example, you have a db column Adjustment, which is a money type that allows null values. However, in your c# class, it is of type decimal, which does not accept null values. There are also some other properties that are either not present, or the types don't match up.

Good news is that fixing it should be really easy if you are using database-first. It's as simple as going to your .edmx file, right-clicking an empty area, and choosing "Update Model from Database".

enter image description here

From there you can add, update, or delete items found in your database. Once you save the model file VS will recreate your model classes, and it should be synced up.

Just a note: if you rename a db column, VS will not delete the old column name from your model, and will throw errors until you delete the column from your code model manually.