错误信息:

“自数据库创建以来,支持‘AddressBook’上下文的模型已经发生了变化。手动删除/更新数据库,或者调用database。带有IDatabaseInitializer实例的SetInitializer。例如,RecreateDatabaseIfModelChanges策略将自动删除并重新创建数据库,并可选地为其添加新数据。”

我正在尝试使用代码优先功能,以下是我写的:

var modelBuilder = new ModelBuilder();
var model = modelBuilder.CreateModel();
using (AddressBook context = new AddressBook(model))
{
    var contact = new Contact
    {
        ContactID = 10000,
        FirstName = "Brian",
        LastName = "Lara",
        ModifiedDate = DateTime.Now,
        AddDate = DateTime.Now,
        Title = "Mr."

    };
    context.contacts.Add(contact);
    int result = context.SaveChanges();
    Console.WriteLine("Result :- "+ result.ToString());
}

上下文类:

public class AddressBook : DbContext
{
    public AddressBook()
    { }
    public AddressBook(DbModel AddressBook)
        : base(AddressBook)
    {

    }
    public DbSet<Contact> contacts { get; set; }
    public DbSet<Address> Addresses { get; set; }
}

和连接字符串:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <connectionStrings>
    <add name="AddressBook" providerName="System.Data.SqlClient"  
         connectionString="Data Source=MyMachine;Initial Catalog=AddressBook;
         Integrated Security=True;MultipleActiveResultSets=True;"/>
    </connectionStrings>
</configuration>

因此,数据库名称是“AddressBook”,当我试图将联系人对象添加到上下文时发生错误。我遗漏了什么吗?


当前回答

以防有人遇到和我一样的情况。

我有数据库首先EF,同时使用asp.net身份

所以我在我的webconfig中有两个connectionStrings,这没有问题。碰巧我创建/运行脚本手动生成asp.net标识表,我不应该这样做。

所以首先DROP所有的asp.net标识表,由你手工创建/从脚本。

DROP TABLE __MigrationHistory
DROP TABLE AspNetRoles
DROP TABLE AspNetUserClaims
DROP TABLE AspNetUserLogins
DROP TABLE AspNetUserRoles
DROP TABLE AspNetUsers

其他回答

我花了很多天来解决这个问题,分析了很多不同的帖子,尝试了很多选择,最终解决了这个问题。 这2个项目在我的解决方案使用EF代码第一次迁移:

控制台应用程序“DataModel”,主要用作程序集,其中包含我所有的代码第一个实体,DbContext, Mirgations和通用存储库。我在这个项目中包含了单独的空本地数据库文件(在DataModel/App_Data文件夹中),以便能够从包管理器控制台生成迁移。 WebApi引用了DataModel项目,并使用了WebApi/App_Data文件夹中的本地数据库文件,该文件不包含在项目中

当请求WebApi时,我得到了这个错误…

我的环境:

Windows 8.1 x64 Visual Studio 2015 Professional with Update 1 我所有的项目都针对。net Framework 4.6.1 EntityFramework 6.1.3 from NuGet

在这里,我收集了所有你应该注意的事项和所有必须满足的条件/要求,以避免提到的例外:

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. 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"){} ... 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.

在对这个主题进行了一些研究之后,我发现如果您之前在本地sql server express上创建了一个db实例,就会发生这个错误。因此,无论何时你在db上有更新,并试图更新db/在db上运行一些代码,而不使用包管理器控制台运行更新数据库命令;首先,您必须手动删除本地SQL express上以前的db。

此外,除非你的配置中有AutomaticMigrationsEnabled = false;,否则这个解决方案是有效的。

如果你使用版本控制系统(git,svn等)和其他一些开发人员在生产阶段更新db对象,那么每当你更新代码库并运行应用程序时,这个错误就会出现。

如上所述,在代码基础上有一些解决方案。然而,在某些情况下,这是最实用的方法。

或者你可以把这一行放在你的Global.asax.cs文件中的Application_Start():

System.Data.Entity.Database.SetInitializer(new System.Data.Entity.DropCreateDatabaseIfModelChanges<ProjectName.Path.Context>());

确保将ProjectName.Path.Context更改为您的名称空间和上下文。如果先使用代码,那么每当对模式进行任何更改时,都会删除并创建一个新数据库。

这意味着上下文上的一些更改还没有执行。 请先运行Add-Migration来生成我们所做的更改(我们可能没有意识到的更改) 然后运行Update-Database

对我来说,在升级到4.3.1之后,我只是截断了EdmMetaData表,或者直接删除它。