Why is EF saying my model has changed when it has not?

asp.net-mvc asp.net-mvc-5.2 c# entity-framework-6 sql-server


I continue to get the same error:

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

I'm using the most recent Entity Framework from Nuget, v6.1.3, to build a.NET MVC 5 website. Since I don't have SQL Server or Express installed locally, I'm attaching a local MDF file. I use the Code First methodology.

I've been looking through SO and web articles on this topic for hours yesterday and today, but I haven't found a solution that works. The majority of them centre on various kinds of initializers or provide succinct justifications for why code initially needs migrations or initializers for model changes. However, I am manually managing the configuration using the PM console. Below are the steps I took.

Relationship String:

<add name="testSQLConnection" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\jwatts\Documents\Visual Studio 2015\Projects\MyProject\Databases\MyProject01.mdf;Integrated Security=True;Connect Timeout=30" providerName="System.Data.SqlClient" />

The example:

public class Family
    public Family() { }

    [Key, Index(IsUnique = true)]
    [Column(Order = 0)]
    public int Id { get; set; }

    public string Name { get; set; }

    public string Description { get; set; }

    public DateTime Created { get; set; }

    public string CreatedBy { get; set; }

    public DateTime? Changed { get; set; }

    public string ChangedBy { get; set; }

    public DateTime? Deleted { get; set; }

    public string DeletedBy { get; set; }

The Situation:

public class McContext : DbContext
    public McContext() : base("testSQLConnection") { }

    public DbSet<Family> Families { get; set; }

The arrangement:

internal sealed class Configuration : DbMigrationsConfiguration<Data.McContext>
    public Configuration()
        MigrationsDirectory = @"Data\Migrations";
        AutomaticMigrationsEnabled = false;
        AutomaticMigrationDataLossAllowed = false;

    protected override void Seed(McContext context)
        context.Families.Add(new Family()
            Name = "My Family",
            Description = "The family",
            Created = DateTime.Now,
            CreatedBy = "system"

Migration class created automatically:

public partial class StartupConfig : DbMigration
    public override void Up()
            c => new
                    Id = c.Int(nullable: false, identity: true),
                    Name = c.String(nullable: false, maxLength: 128),
                    Description = c.String(maxLength: 1024),
                    Created = c.DateTime(nullable: false),
                    CreatedBy = c.String(),
                    Changed = c.DateTime(),
                    ChangedBy = c.String(),
                    Deleted = c.DateTime(),
                    DeletedBy = c.String(),
            .PrimaryKey(t => t.Id)
            .Index(t => t.Id, unique: true);


    public override void Down()
        DropIndex("dbo.Families", new[] { "Id" });

Code for unit tests:

public void CreateTheContext_Test()
    using (var ctx = new McContext())
        //error on this line below:
        var fam = ctx.Families.Where(f => f.Name.Contains("My")).FirstOrDefault();
        Assert.IsTrue(fam != null && fam.Name.Contains("My"));

Exercise steps:

  1. I created a "blank slate" by deleting all database tables and Data Migrations from my test database.
  2. Rebuild the answer. (The basic project plus a project for unit testing)
  3. Run "in the Package Manager Console"Add-Migration StartupConfig "
  4. DataMigrations receives a new migration file named "{datetime}_StartupConfig.cs ". SeeStartupConfig class higher.
  5. It was a project I made.
  6. I ran "Update-Database -TargetMigration:StartupConfig "
  7. The "Running Seed technique" is one of four lines that the PM console emits after successfully completing.
  8. I verified with a SQL query that the__MigrationHistory " and "Families " table, each of which contains one entry, has been added to the database.
  9. I attempted the unit test and got the issue.

I started by simplifying my more complicated model by deleting components one by one. I can't make it much easier than this, yet the mistake still occurs. Notably, I have never seen a successful query come from the unit test for this specific project.

When I tried to recreate the aforementioned steps as I was typing them down, I encountered the same issue.

What should I attempt next, exactly?

9/25/2017 1:06:21 AM

Accepted Answer

As suggested by @AaronLS, I checked the connection string in the Unit Test and discovered that it was different.

It turned out that the App.config for the Unit Test was missing the connection string and was using "sqlTestConnection" as the database name since it was unable to resolve it any other way.

The problem was fixed by including the connection string in the App.config file.

9/25/2017 1:30:39 AM

Popular Answer


Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow