90

First of all, I have not seen this error anywhere else and I guess it's not a replicate so please read the whole situation first.

Everything was working just fine then I tried to update one of my model classes ( the App class and the update is now left commented ) which I will be listing below; and boom I had this ugly error.


The model backing the 'ApplicationDbContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269). at System.Data.Entity.CreateDatabaseIfNotExists1.InitializeDatabase(TContext context) at System.Data.Entity.Internal.InternalContext.<>c__DisplayClassf1.b__e() at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action) at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization() at System.Data.Entity.Internal.LazyInternalContext.b__4(InternalContext c) at System.Data.Entity.Internal.RetryAction1.PerformAction(TInput input) at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action1 action) at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase() at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) at System.Data.Entity.Internal.Linq.InternalSet1.Initialize() at System.Data.Entity.Internal.Linq.InternalSet1.Include(String path) at System.Data.Entity.Infrastructure.DbQuery1.Include(String path) at System.Data.Entity.QueryableExtensions.Include[T](IQueryable1 source, String path) at System.Data.Entity.QueryableExtensions.Include[T,TProperty](IQueryable1 source, Expression1 path) at Microsoft.AspNet.Identity.EntityFramework.UserStore6.GetUserAggregateAsync(Expression1 filter) at Microsoft.AspNet.Identity.EntityFramework.UserStore6.FindByNameAsync(String userName) at Microsoft.AspNet.Identity.UserManager2.FindByNameAsync(String userName) at Microsoft.AspNet.Identity.UserManager`2.d__12.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at ControlPanel.Web.Controllers.AccountController.d__2.MoveNext() in d:\Projects\FULL\Control Panel\ControlPanel.Web\Controllers\AccountController.cs:line 56

At first I thought it might be a migrations problem, so I dropped the database entirely, re-enabled the migrations, and added an Init migration and updated the database using

update-database -force -verbose

Everything goes well with no complaints, however, whenever I try to log in to my site I get the previous error. I did the migration thing about ten times without being able to solve the problem.

Here are my domain classes ( models ):

public class App
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public virtual int AppId { get; set; }
    //[Required]
    public virtual string FacebookId { get; set; }
    //[Required]
    public virtual string Secret { get; set; }      
    public virtual List<User> Users { get; set; }
    public virtual List<Post> Posts { get; set; }      
    //public virtual ApplicationUser Admin { get; set; }
}

public class Post
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public virtual int PostId { get; set; }
    public virtual string Content { get; set; }
    public virtual string Link { get; set; }
    public virtual string Image { get; set; }
    public virtual bool IsSpecial { get; set; }
    //[Required]
    public virtual App App { get; set; }
    //[Required]
    public virtual DateTime? PublishDate { get; set; }
}

public class User
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public virtual int UserId { get; set; }

    [MaxLength(500)]
    public virtual string FacebookId { get; set; }

    [MaxLength(500)]
    public virtual string Token { get; set; }

    //[Required]
    public virtual App App { get; set; }
}

Here are my IdentityModels:

public class ApplicationUser : IdentityUser
{
    public virtual List<App> Apps { get; set; }
    public bool? IsPremium { get; set; }
    [DataType(DataType.Date)]
    public DateTime? LastPublishDateTime { get; set; }
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("dCon")
    {
    }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<IdentityUser>().ToTable("Admins");
        modelBuilder.Entity<ApplicationUser>().ToTable("Admins");
        modelBuilder.Entity<IdentityUserRole>().ToTable("AdminRoles");
        modelBuilder.Entity<IdentityUserLogin>().ToTable("Logins");
        modelBuilder.Entity<IdentityUserClaim>().ToTable("Claims");
        modelBuilder.Entity<IdentityRole>().ToTable("Roles");
    }
}
Ahmad Hamdi
  • 1,227
  • 1
  • 11
  • 17
  • Are you sure you haven't seen this problem elsewhere? What about this link? http://stackoverflow.com/questions/3600175/the-model-backing-the-database-context-has-changed-since-the-database-was-crea – AndreCruz Mar 14 '14 at 15:05
  • 4
    No, they are not the same I can assure you,, I've tried the solution provided there with no results at all,, their error says : Either manually delete/update the database,, whereas mine says : Consider using Code First Migrations to update the database – Ahmad Hamdi Mar 15 '14 at 03:39

20 Answers20

146

Just in case anyone else stumbles upon this that was doing a database first implementation like me.

I made a change by extending the ApplicationUser class, adding a new field to the AspNetUsers table, and then had this error on startup.

I was able to resolve this by deleting the record created in the __MigrationHistory table (there was only one record there) I assume EF decided that I needed to update my database using the migration tool - but I had already done this manually myself.

Divyang Desai
  • 7,483
  • 13
  • 50
  • 76
Josh
  • 3,442
  • 2
  • 23
  • 24
  • 1
    Database first as well and this fixed it. The only record there was the initial create which did happen code first, but I modified it after using database first and changing the table in MS SQL server. – SolidSnake4444 Sep 15 '15 at 19:34
  • Worked. I got the error when I added a scaffolded view. The view's **data context class** was `ApplicationDbContext` – Vincent Saelzler Apr 07 '16 at 18:13
86

This worked for me - no other changes required.

DELETE FROM [dbo].[__MigrationHistory]
Daniel de Zwaan
  • 3,064
  • 25
  • 24
  • 1
    Worked for me too. Very strange fix. I think, there was a broken migration in the history. I will try to delete all migrations and create initial one again. – hakan Jul 16 '15 at 22:41
  • 1
    @Dave Voyles you can run this SQL directly in SSMS – Daniel de Zwaan Nov 03 '15 at 04:27
  • 1
    Worked for me too.In one database this table existed whereas it dint exist in another database – Tejas Apr 20 '16 at 13:33
  • 1
    Above answers can't help me since my codes were running fine until the last model update. Your answer did the trick. Cheers man!! – Sithu Aug 01 '16 at 09:29
  • 4
    This DIDN'T work for me, and caused me to need to delete the db, re-run the migrations and re-add the data. BEWARE. – adamonstack Feb 11 '17 at 17:58
  • 1
    Always do a database backup before you delete all the records from a table. I'm a pupil of the "just in case" philosophy. :) – John Waclawski Oct 13 '17 at 19:41
  • 1
    This worked for me too. But WHY? I checked the history, nothing seems wrong, is this some sort of bug? – Iyad Jul 23 '18 at 13:44
  • 1
    Weird problem!! but thanks for your solution it works! at least they should provide a proper clue what to do in 2019! – noman404 May 13 '19 at 14:58
  • DON'T DO THIS -- you will never be able to migrate again. Might as well nuke your database and start over. – Meekohi Apr 28 '21 at 16:06
  • 1
    Worked for me as well. Strange, but easy fix. – JayTeeEye Oct 03 '22 at 15:06
35

This post fixed my issue. It's all about adding the following line in Application_Start() in Global.asax :

Database.SetInitializer<Models.YourDbContext>(null);

However it cause database recreation for every edit in your model and you may loose your data.

Amin Saqi
  • 18,549
  • 7
  • 50
  • 70
15

If you delete the "[__MigrationHistory]" table from your "database > System Tables" then it will work.

Ishwor Khanal
  • 1,312
  • 18
  • 30
Aniket Sharma
  • 1,000
  • 10
  • 16
  • It works. But after deleteing `[__MigrationHistory]` table just update EDMX mmodel as well. – NoWar Aug 30 '18 at 01:23
12

It was such a strange error,, It wasn't my error at the end, it was Microsoft's,, I installed the Entity framework the " pre-release" version and it was responsible for this error,, when i upgraded to the stable release it disapperared,, thank you everyone believe me when i asked this question i searched like for a week or so for its solution so i am pretty sure that this problem isn't anywhere else : the version of entity framework.dll that caused the problem was 6.0.2 if it helps.

Ahmad Hamdi
  • 1,227
  • 1
  • 11
  • 17
12

Everybody getting a headache from this error: Make absolutely sure all your projetcs have a reference to the same Entity Framework assembly.

Short story long:

My model and my application were in different assemblies. These assemblies were referencing a different version of Entity framework. I guess that the two versions generated a different id for the same modell. So when my application ran the id of the model didn't match the one of the latest migration in __MigrationHistory. After updating all references to the latest EF release the error never showed up again.

Hari
  • 4,514
  • 2
  • 31
  • 33
  • yes, that was my case, most projects was with ef6.1.3, while the newly created test project was somehow with ef6.0. – ZZZ May 19 '17 at 21:26
6

I spent many days to solve this issue, analyzed many different posts and tried many options and finally fixed. This 2 projects in my solution using EF code first migrations:

  • Console Application "DataModel" that mainly using as assembly which contains all my code first entities, DbContext, Mirgations and generic repository. I have included to this project separate empty local database file (in DataModel/App_Data folder) to be able generate migrations from Package Manager Console.
  • WebApi, which references to DataModel project and uses local database file from WebApi/App_Data folder, that not included in project

I got this error when requested WebApi...

My environment:

  • Windows 8.1 x64
  • Visual Studio 2015 Professional with Update 1
  • all my projects targeted for .NET Framework 4.6.1
  • EntityFramework 6.1.3 from NuGet

Here I collected all the remarks you should pay attention and all conditions/requirements which must be met, to avoid mentioned exception :

  1. You should use only one version of EntityFramework Nuget package for all projects in your solution.
  2. Database, created by running sequentially all migration scripts should have the same structure/schema as you target database and correspond to entity model. Following 3 things must exactly correspond/reflect/match each other:
    • Your all migration script up to last
    • Current code first entity model state (DbContext, entities)
    • Target database
  3. Target database (mdf file) should be updated/correspond up to last migration script. Verify that "__MigrationHistory" table in your target database contains records for all migration scripts that you have, it means that all migration scripts was successfully applied to that database. I recommend you to use Visual Studio for generation correct code first entities and context that corresponds to your database, Project -> Add New Item -> ADO.NET Entity Data Model -> Code First from database: Of course, as an alternative, if you have no database you can write manually model (code first entities and context) and then generate initial migration and database.
  4. Name of connection string e.g. MyConnectionString in config file of startup project (Web.config/App.config):

    <configuration>
      <connectionStrings>
        <add name="MyConnectionString" connectionString="...">
      </connectionStrings>
    <configuration>
    

    should be equal to parameter passed in constructor of your DbContext:

     public partial class MyDbContext : DbContext
     {
        public MyDbContext()
           : base("name=MyConnectionString"){}
        ...
    
  5. Before using Package Manager Console, make sure that you are using correct database for update or generate migration and needed project is set as startup project of solution. For connect to database it will use connection string from that .config file, which in project, that is set as startup project.
  6. And the main, which fixed my issue: It is weird, but in my WebApi/bin folder DataModel.exe was old, not refreshed since last build. Since migrations was embedded in my assembly DataModel.exe then my WebApi updated database using old mirgations. I was confused why after updating database in WebApi it not corresponds to latest migration script from DataModel. Following code automatically creates(if not exists) or updates to latest migration local database in my WebApi/App_Data folder.

       public class WebApiApplication : System.Web.HttpApplication
       {
           protected void Application_Start()
           {
               Database.SetInitializer(new MigrateDatabaseToLatestVersion<ODS_DbContext, Configuration>()); 
               ...
    

    I tried clean and rebuild solution but it did not help, than I completely removed bin and obj folders from WebApi, deleted database files from WebApi/App_Data, built, restarted WebApi, made request to it, it created correct database - lazy initialization (using lines above), which corresponds to latest migration and exception didn't appear more. So, this may fix your problem:

    1. remove manually bin, obj folders from your startup project (which generates/updates your database)
    2. build your startup project or better clean and rebuild all you solution.
    3. recreate database by starting project (will execute lines above) or use Package Manager Console "update-database" command.
    4. manually check whether generated db and __MirgationHistory corresponds to latest migration script.
Sergey Kulgan
  • 1,215
  • 1
  • 12
  • 12
3

This can happen when you change the data annotation of a model property. for example: adding [Required] to a property will cause a pending change in the database design.

The safest solution is to run on the Package Manager Console:

add-migration myMirgrationName

which will display the exact changes in the Up() method. Therefore, you can decide if you really want to apply such changes via the:

update-database

Otherwise, you may just delete the latest migration from the __MigrationHistory table and from the Migrations folder the Solution Explorer.

Mohamed Nagieb
  • 819
  • 9
  • 11
  • This is definitely the best answer I have seen here. The suggestion of deleting the migration history is a very bad idea in my opinion! – mgrenier Oct 09 '18 at 23:59
  • Thanks for your comment. I also don't usually recommend deleting migration history, but in particular case, the previous migration point wasn't too different - i.e. no much model modifications had been occurred by the OP -, so I thought may be a single step back can help, by deleting only the very last migration(s) records. – Mohamed Nagieb Oct 15 '18 at 22:56
3

Just Delete the migration History in _MigrationHistory in your DataBase. It worked for me

k.demas
  • 41
  • 2
2

I was having same problem as a7madx7, but with stable release of EF (v6.1.1), and found resolution posted in:

http://cybarlab.com/context-has-changed-since-the-database-was-created

with variation in: http://patrickdesjardins.com/blog/the-model-backing-the-context-has-changed-since-the-database-was-created-ef4-3

2nd link includes specific mention for VB..... "you can simply add all the databasecontext that are having this problem on your app_start method in the global.asax file like this":

Database.SetInitializer(Of DatabaseContext)(Nothing)

NB: i had to replace "DatabaseContext" with the name of my class implementing DbContext

Update: Also, when using codefirst approach to connect to existing tables, check database to see if EF has created a table "_migrationhistory" to store mappings. I re-named this table then was able to remove SetInitializer from global.asax.

user3085342
  • 86
  • 1
  • 6
1

From the Tools menu, click NuGet Package Manger, then click Package Manager Console (PMC). Enter the following commands in the PMC.

Enable-Migrations Add-Migration Init Update-Database Run the application. The solution to the problem is from here

Sultan
  • 701
  • 1
  • 6
  • 19
1

When I am developing, I prefer to use this practical class to configure Migrations.

Hope it helps.

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
        this.Configuration.LazyLoadingEnabled = false;
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
        modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();

        Database.SetInitializer(new StackOverflowInitializer());
    }

    public class StackOverflowInitializer : DropCreateDatabaseIfModelChanges<ApplicationDbContext>
    {
        public StackOverflowInitializer()
        {
            // TODO NOTHING, COMMENT ALL

            // IF CHANGES, RECREATE
            Database.SetInitializer(new DropCreateDatabaseIfModelChanges<ApplicationDbContext>());

            // CREATE ONLY NOT EXITS
            //Database.SetInitializer<Context>(new CreateDatabaseIfNotExists<ApplicationDbContext>());
        }

    }

    public System.Data.Entity.DbSet<stackoverflow.Models.Company> Companies { get; set; }

}
Andre Mesquita
  • 879
  • 12
  • 25
0

I just solved a similar problem by deleting all files in the website folder and then republished it.

Daniel Björk
  • 2,475
  • 1
  • 19
  • 26
0

Deleting Rows in [__MigrationHistory] table with Older productVersion worked for me. This answer is for those who don't want to delete entire [__MigrationHistory] table. Just delete the rows with older version in ProductVersion Column. Hope it helps some one!

Rajon Tanducar
  • 308
  • 4
  • 8
0

Below was the similar kind of error i encountered

The model backing the 'PsnlContext' 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 added the below section in the Application Start event of the Global.asax to solve the error

Database.SetInitializer (null);

This fixed the issue

Lati
  • 1
  • 1
0

simply the error means that your models has changes and is not in Sync with DB ,so go to package manager console , add-migration foo2 this will give a hint of what is causing the issue , may be you removed something or in my case I remove a data annotation . from there you can get the change and hopefully reverse it in your model.

after that delete foo2 .

0

I know I am very late, but I want to give contribution too. This error is really strange, because the browser is not able to understand how the changes should be rendered because the classes and their properties might have changed but not committed to the database.

So do one thing,

create one migration in Package Manager Console(Tools > NuGet Package Manager > Package Manager Console) using this command:

add-migration UpdateMigration

where UpdateMigration is the name of your Migration. You can give it any name of your choice but please be specific.

After that, we just need to update the database, so run this:

update-database

Now that you have committed your changes to the database, just refresh your browser and there you go!

Hope this helps.

Rohan Rao
  • 2,505
  • 3
  • 19
  • 39
0

this comes because you add some property to one of your model and you did not update-Database . to solve this you have to remove it from model or you have to add-migration anyProperName with that properties and Update-database.

HeshanHH
  • 653
  • 7
  • 9
0

This error occurred to me when I made changes to my Model and did not make migration for the changes to update the database.

If you have ever made changes to your model in Code First Migration Schema

Don't forget to add migration

add-migration UpdatesToModelProperites 

The above command will read all the changes you have made in the model and will write it in the Up() and Down() methods.

Then simply update your database using the below command.

update-database

This what worked for me.

Raheel Khan
  • 464
  • 10
  • 12
-2

Delete existing db ,create new db with same name , copy all data...it will work

faux
  • 91
  • 1
  • 10