The model supporting the "ApplicationDbContext" context has changed since the database was created.

First of all, I have not seen this error anywhere else, and I think this is not a copy, so please read the whole situation first.

Everything worked fine, then I tried to update one of my model classes ( the App class and the update is now left in the comments), which I will list below, and that I had this ugly error.




The model supporting the ApplicationDbContext context has changed since the database was created. It is recommended that you use Code First Migrations to update the database ( http://go.microsoft.com/fwlink/?LinkId=238269 ). in System.Data.Entity.CreateDatabaseIfNotExists 1.InitializeDatabase(TContext context) at System.Data.Entity.Internal.InternalContext.<>c__DisplayClassf 1.b__e () in System.Data.Entity.Internal.InternalContext.PerformInitializationActionalizationAction .Data.Entity.Internal.InternalContext.PerformDatabaseInitialization () in System.Data.Entity.Internal.LazyInternalContext.b__4 (InternalContext c) in System.Data.Entity.Internal.RetryAction 1.PerformAction(TInput input) at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action . 1.Initialize() at System.Data.Entity.Internal.Linq.InternalSet 1.Include (string path) in System.Data.Entity.Infrastructure.DbQuery 1.Include(String path) at System.Data.Entity.QueryableExtensions.Include[T](IQueryable 1.Include(String path) at System.Data.Entity.QueryableExtensions.Include[T](IQueryable 1.Include(String path) at System.Data.Entity.QueryableExtensions.Include[T](IQueryable 1 source, string path) in System.Data.Entity.QueryableExtensions.Include [T, TProperty] ( 1 source, Expression IQueryable 1 source, Expression path 1 source, Expression 1) in Microsoft.AspNet .Identity.EntityFramework.UserStore 6.GetUserAggregateAsync(Expression filter 6.GetUserAggregateAsync(Expression 1) in Microsoft.AspNet.Identity.EntityFramework.UserStore 6.FindByNameAsync(String userName) at Microsoft.AspNet.Identity.UserManager 2.ame ) in Microsoft.AspNet.Identity.UserManager'2.d__12.MoveNext (The end of the stack trace from the previous location where the exception was thrown --- in System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (Task) in System.Runtime.CompilerServices .TaskAwaiter.HandleNonSuccessAndDebuggerNotification (Task TaskControl.A..d__2.MoveNext () in d: \ Proje cts \ FULL \ Control Panel \ ControlPanel.Web \ Controllers \ AccountController.cs: line 56

At first, I thought it might be a migration problem, so I completely deleted the database, turned on the migration again, added the Init migration, and updated the database using

 update-database -force -verbose 

Everything is going well, without any complaints, but whenever I try to access my site, I get a previous error. I migrated about ten times, unable 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"); } } 
+79
linq asp.net-mvc entity-framework asp.net-mvc-5
Mar 14 '14 at 15:01
source share
18 answers

It was such a strange mistake. It was not my mistake at the end, it was Microsoft, I installed the Entity framework in the “before release” version, and he was responsible for this error, when I updated to the stable release it disappeared, thanks to everyone who believes me, when I asked this the question I was looking for, for example, a week or so to solve it, so I'm sure this problem is not somewhere else: the entity framework.dll version that caused the 6.0.2 problem if that helps.

+11
Mar 15 '14 at 6:12
source share

Just in case, someone stumbles upon this, which makes the first database implementation, like me.

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

I was able to solve this problem by deleting the record created in the __MigrationHistory table (there was only one record there). I believe that EF decided that I need to update my database using the migration tool, but I already did it manually.

+128
Sep 18 '14 at 0:57
source share

This worked for me - no other changes were required.

 DELETE FROM [dbo].[__MigrationHistory] 
+66
May 25 '15 at 7:18
source share

This post fixed my problem. All about adding the following line to Application_Start() in Global.asax :

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

However, this causes a database recovery for each edit in your model, and you may lose your data.

+31
Apr 09 '14 at 11:00
source share

Everyone gets a headache from this error: Make sure all your projetcs have a link to the same Entity Framework build.

Short story:

My model and my application were in different assemblies. These assemblies referred to a different version of the Entity infrastructure. I assume that the two versions generated a different identifier for the same module. Therefore, when my application ran the model identifier, it did not match one of the last migrations in __MigrationHistory. After updating all links to the latest version of EF, the error never appeared again.

+11
Sep 11 '14 at 16:18
source share

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

+9
Dec 22 '16 at 10:34
source share

I spent many days to solve this problem, analyzed many different messages and tried many options and finally fixed . These are 2 projects in my solution using the first migrations of the EF code:

  • Console application "DataModel", which is mainly used as an assembly, which contains all my first code objects, DbContext, Mirgations and a common repository. I included a separate empty local database file (in the DataModel / App_Data folder) in this project in order to be able to generate a migration from the package manager console.
  • WebApi, which refers to the DataModel project and uses the local database file from the WebApi / App_Data folder, which is not included in the project

I got this error when requesting WebApi ...

My environment:

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

Here I have collected all the comments that you should pay attention to, and all the conditions / requirements that must be met in order to avoid the mentioned exception:

  • You should use only one version of the EntityFramework Nuget package for all projects of your solution.
  • A database created by sequentially launching all migration scenarios should have the same structure / scheme as the target database and match the entity model. The following 3 things must exactly match / reflect / match each other:
    • All your migration script to the last
    • The current state of the first entity model (DbContext, entity)
    • Target database
  • The target database (mdf file) should be updated / consistent with the latest migration script. Make sure that the __MigrationHistory table in your target database contains entries for all the migration scripts that you have, which means that all migration scripts have been successfully applied to this database. I recommend that you use Visual Studio to generate the correct first entity and context codes appropriate for your database, Project → Add New Item → ADO.NET Entity Data Model → Code First from the database: Of course, as an alternative, if you do not have a database, you can write the model manually (code of the first entities and context), and then create the initial migration and database.
  • The name of the connection string, for example. MyConnectionString in the project launch configuration file (Web.config / App.config):

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

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

      public partial class MyDbContext : DbContext { public MyDbContext() : base("name=MyConnectionString"){} ... 
  • Before using the Package Manager Console , make sure that you are using the correct database to update or create the migration, and that the required project is set up as the launch project of the solution. . To connect to the database, it will use the connection string from this .config file, which is in the project that is specified as the launch project.
  • And the main question that fixed my problem: This is strange, but in my folder WebApi / bin DataModel.exe was old, it has not been updated since the last build. Since migrations were built into my DataModel.exe assembly, my updated WebApi database used old mirrors. I was confused why after updating the database in WebApi it does not match the last migration script from the DataModel. The following code automatically creates (if it does not exist) or updates the last local local migration 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 to clean and rebuild the solution, but it did not help, than I completely removed bin and obj from WebApi, deleted database files from WebApi / App_Data, built-in, restarted WebApi, made a request to it, created the correct database - lazy initialization (using line above), which corresponds to the last migration and the exception was no longer displayed. So, this can solve your problem:

    • manually delete bin, obj folders from your startup project (which generates / updates your database)
    • create your startup project or better clean and rebuild all your decisions.
    • recreate the database by running the project (following the lines above) or use the "Update-database" command of the package manager.
    • manually check if the generated db and __MirgationHistory match the latest migration script.
+7
Jan 14 '16 at 22:09
source share

I had the same problem as a7madx7, but with stable release of EF (v6.1.1) and found a resolution published in:

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

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

The second link includes a specific mention for VB ..... "you can just add all databasecontext that have this problem in your app_start method in a global.asax file like this":

 Database.SetInitializer(Of DatabaseContext)(Nothing) 

NB: I had to replace "DatabaseContext" with the name of my class that implements DbContext

Update. Also, when using the codefirst approach to connect to existing tables, check the database to see if EF has created the _migrationhistory table to store the mappings. I renamed this table, after which I was able to delete SetInitializer from global.asax.

+2
Jul 29 '14 at 4:48
source share

This can happen when the annotation of the model property data changes. for example: adding [Required] to a property will cause pending changes to 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 whether you really want to apply such changes with:

 update-database 

Otherwise, you can simply delete the last migration from the __MigrationHistory table and from the Migrations folder in Solution Explorer.

+2
Mar 18 '18 at 21:55
source share

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

+1
May 10 '14 at 22:53
source share

delete all table identifiers

 Delete _MigrationHistory Delete AspNetRoles Delete AspNetUserClaims Delete AspNetUserLogins Delete AspNetRoles Delete AspNetUser 
+1
May 20 '16 at 19:42
source share

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

Enable-Migrations Add-Migration Init Update-Database Launch the application. Solution to the problem from here

+1
Jan 16 '18 at 3:41
source share

Deleting rows in the [__MigrationHistory] table using an older version of the product worked for me. This answer is for those who do not want to delete the entire table [__MigrationHistory]. Just delete the lines with the old version in the ProductVersion column. Hope this helps someone!

0
Feb 20 '18 at 5:52
source share

When I'm developing, I prefer to use this practical class to configure migration.

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; } } 
0
Apr 20 '18 at 3:13
source share

Below was a similar error that I encountered

The model supporting the PsnlContext context has changed since the database was created. It is recommended that you use Code First Migrations to update the database ( http://go.microsoft.com/fwlink/?LinkId=238269 ).

I added the section below to the Global.asax application launch event to fix the error

Database.SetInitializer (null);

This solved the problem.

0
Jul 29 '18 at 5:50
source share

Just delete the migration history in _MigrationHistory. It worked for me

0
Feb 01 '19 at 21:09
source share

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

-one
Jun 20 '17 at 6:34
source share

Add the line below inside "Application_Start" to "Global.asax.cs"

 Database.SetInitializer<YourDbContext>(new DropCreateDatabaseIfModelChanges<YourDbContext>()); 
-one
Jul 22 '18 at 17:03
source share



All Articles