.net 自创建数据库以来,支持“ApplicationDbContext”上下文的模型已更改
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22408608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
The model backing the 'ApplicationDbContext' context has changed since the database was created
提问by a7madx7
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 classand the update is now left commented ) which I will be listing below; and boom I had this ugly error.
一切正常,然后我尝试更新我将在下面列出的模型类之一(App 类和更新现在留下评论);和繁荣我有这个丑陋的错误。
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.CreateDatabaseIfNotExists
1.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
自数据库创建以来,支持“ApplicationDbContext”上下文的模型已更改。考虑使用 Code First 迁移来更新数据库 ( http://go.microsoft.com/fwlink/?LinkId=238269)。在 System.Data.Entity.CreateDatabaseIfNotExists
1.InitializeDatabase(TContext context) at System.Data.Entity.Internal.InternalContext.<>c__DisplayClassf1.b__e() 在 System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action) 在 System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization() 在 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) 在 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 过滤器)在 Microsoft.AspNet.Identity.EntityFramework.UserStore6.FindByNameAsync(String userName) at Microsoft.AspNet.Identity.UserManager2.FindByNameAsync(String userName) 在 Microsoft.AspNet.Identity.UserManager`2.d__12.MoveNext() --- 从上一个位置的堆栈跟踪结束异常被抛出 --- 在 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 firstI 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
起初我认为这可能是一个迁移问题,所以我完全删除了数据库,重新启用了迁移,并添加了一个 Init 迁移并使用更新了数据库
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:
这是我的 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");
}
}
采纳答案by a7madx7
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.
这是一个如此奇怪的错误,最后不是我的错误,而是微软的,我安装了实体框架的“预发布”版本并且它对这个错误负责,当我升级到稳定版时释放它消失了,谢谢大家相信我,当我问这个问题时,我搜索了一周左右的解决方案,所以我很确定这个问题不在其他任何地方:导致如果有帮助,问题是 6.0.2。
回答by Josh
Just in case anyone else stumbles upon this that was doing a database first implementation like me.
以防万一其他人偶然发现了像我这样的数据库优先实现。
I made a change by extending the ApplicationUserclass, adding a new field to the AspNetUserstable, and then had this error on startup.
我通过扩展ApplicationUser类进行了更改,向AspNetUsers表中添加了一个新字段,然后在启动时出现此错误。
I was able to resolve this by deleting the record created in the __MigrationHistorytable (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.
我能够通过删除__MigrationHistory表中创建的记录来解决这个问题(那里只有一条记录)我假设 EF 决定我需要使用迁移工具更新我的数据库 - 但我已经自己手动完成了。
回答by Daniel de Zwaan
This worked for me - no other changes required.
这对我有用 - 不需要其他更改。
DELETE FROM [dbo].[__MigrationHistory]
回答by Amin Saqi
This postfixed my issue. It's all about adding the following line in Application_Start()in Global.asax:
这篇文章解决了我的问题。这就是在Application_Start()in 中添加以下行Global.asax:
Database.SetInitializer<Models.YourDbContext>(null);
Database.SetInitializer<Models.YourDbContext>(null);
However it cause database recreation for every edit in your model and you may loose your data.
但是,它会导致模型中每次编辑的数据库重新创建,并且您可能会丢失数据。
回答by Hari
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.
我的模型和我的应用程序在不同的程序集中。这些程序集引用了不同版本的实体框架。我猜这两个版本为同一个模型生成了不同的 id。因此,当我的应用程序运行时,模型的 id 与 __MigrationHistory 中的最新迁移之一不匹配。更新对最新 EF 版本的所有引用后,错误再也没有出现。
回答by Aniket Sharma
If you delete the "[__MigrationHistory]" table from your "database > System Tables" then it will work.
如果您从“数据库 > 系统表”中删除“[__MigrationHistory]”表,那么它将起作用。
回答by Sergey Kulgan
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:
我花了很多天来解决这个问题,分析了很多不同的帖子,尝试了很多选择,最后解决了。我的解决方案中的这 2 个项目使用 EF 代码首先迁移:
- 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
- 控制台应用程序“DataModel”主要用作程序集,其中包含我所有的代码优先实体、DbContext、MiRGations 和通用存储库。我已经在这个项目中包含了单独的空本地数据库文件(在 DataModel/App_Data 文件夹中),以便能够从包管理器控制台生成迁移。
- WebApi,它引用 DataModel 项目并使用 WebApi/App_Data 文件夹中的本地数据库文件,该文件未包含在项目中
I got this error when requested WebApi...
请求 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
- 视窗 8.1 x64
- 带有更新 1 的 Visual Studio 2015 Professional
- 我所有针对 .NET Framework 4.6.1 的项目
- 来自 NuGet 的 EntityFramework 6.1.3
Here I collected all the remarks you should pay attention and all conditions/requirements which must be met, to avoid mentioned exception :
在这里,我收集了您应该注意的所有备注以及必须满足的所有条件/要求,以避免提到的例外情况:
- You should use only one version of EntityFramework Nuget package for all projects in your solution.
- 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
- 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. Name of connection string e.g. MyConnectionStringin 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"){} ...- 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.
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:
- remove manually bin, obj folders from your startup project(which generates/updates your database)
- build your startup project or better clean and rebuild all you solution.
- recreate database by starting project (will execute lines above) or use Package Manager Console "update-database" command.
- manually check whether generated db and __MirgationHistory corresponds to latest migration script.
- 对于解决方案中的所有项目,您应该只使用一个版本的 EntityFramework Nuget 包。
- 通过顺序运行所有迁移脚本创建的数据库应与目标数据库具有相同的结构/模式并对应于实体模型。以下三件事必须完全对应/反映/匹配:
- 您的所有迁移脚本直到最后
- 当前代码第一实体模型状态(DbContext,实体)
- 目标数据库
- 目标数据库(mdf 文件)应更新/对应于上次迁移脚本。验证目标数据库中的“__MigrationHistory”表是否包含您拥有的所有迁移脚本的记录,这意味着所有迁移脚本都已成功应用于该数据库。我建议您使用 Visual Studio 生成与您的数据库对应的正确代码优先实体和上下文,项目 -> 添加新项目 -> ADO.NET 实体数据模型 -> 数据库中的代码优先:
当然,作为替代,如果您没有数据库,您可以手动编写模型(代码优先实体和上下文),然后生成初始迁移和数据库。 连接字符串的名称,例如启动项目配置文件中的MyConnectionString(Web.config/App.config):
<configuration> <connectionStrings> <add name="MyConnectionString" connectionString="..."> </connectionStrings> <configuration>应该等于在你的 DbContext 的构造函数中传递的参数:
public partial class MyDbContext : DbContext { public MyDbContext() : base("name=MyConnectionString"){} ...- 在使用Package Manager Console之前,请确保您使用正确的数据库进行更新或生成迁移,并将所需项目设置为解决方案的启动项目。对于连接到数据库,它将使用该 .config 文件中的连接字符串,该文件在项目中被设置为启动项目。
主要解决了我的问题:这很奇怪,但在我的 WebApi/bin 文件夹中 DataModel.exe 很旧,自上次构建以来没有刷新。由于迁移嵌入在我的程序集 DataModel.exe 中,因此我的 WebApi 使用旧的 mirgations 更新了数据库。我很困惑为什么在 WebApi 中更新数据库后它不对应于来自 DataModel 的最新迁移脚本。以下代码会在我的 WebApi/App_Data 文件夹中自动创建(如果不存在)或更新到最新的迁移本地数据库。
public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { Database.SetInitializer(new MigrateDatabaseToLatestVersion<ODS_DbContext, Configuration>()); ...我尝试了清理和重建解决方案,但没有帮助,我从 WebApi 中完全删除了 bin 和 obj 文件夹,从 WebApi/App_Data 中删除了数据库文件,构建、重新启动了 WebApi,向它发出了请求,它创建了正确的数据库 - 延迟初始化(使用行),这对应于最新的迁移和异常没有出现更多。 因此,这可能会解决您的问题:
- 从您的启动项目中手动删除 bin、obj 文件夹(生成/更新您的数据库)
- 构建您的启动项目或更好地清理和重建您的所有解决方案。
- 通过启动项目(将执行上面的行)或使用包管理器控制台“更新数据库”命令重新创建数据库。
- 手动检查生成的 db 和 __MilgationHistory 是否对应于最新的迁移脚本。
回答by Mohamed Nagieb
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.
当您更改模型属性的数据注释时,可能会发生这种情况。例如:将[Required]添加到属性将导致数据库设计中的未决更改。
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:
这将显示 Up() 方法中的确切更改。因此,您可以通过以下方式决定是否真的要应用此类更改:
update-database
Otherwise, you may just delete the latest migration from the __MigrationHistory table and from the Migrations folder the Solution Explorer.
否则,您可以从 __MigrationHistory 表和解决方案资源管理器的 Migrations 文件夹中删除最新的迁移。
回答by user3085342
I was having same problem as a7madx7, but with stable release of EF (v6.1.1), and found resolution posted in:
我遇到了与 a7madx7 相同的问题,但 EF (v6.1.1) 稳定版本发布,并发现解决方案发布在:
http://cybarlab.com/context-has-changed-since-the-database-was-created
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
变化: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":
第二个链接包含对 VB 的具体提及..... “您可以像这样在 global.asax 文件中的 app_start 方法中简单地添加所有存在此问题的数据库上下文”:
Database.SetInitializer(Of DatabaseContext)(Nothing)
NB: i had to replace "DatabaseContext" with the name of my class implementing DbContext
注意:我必须用我实现 DbContext 的类的名称替换“DatabaseContext”
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.
更新:此外,当使用 codefirst 方法连接到现有表时,请检查数据库以查看 EF 是否已创建表“_migrationhistory”来存储映射。我重命名了这个表,然后就可以从 global.asax 中删除 SetInitializer。
回答by Andre Mesquita
When I am developing, I prefer to use this practical class to configure Migrations.
在开发的时候,我更喜欢用这个实用的类来配置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; }
}

