.net - 自数据库创建以来,支持 <Database> 上下文的模型已发生更改

标签 .net entity-framework-4 code-first

错误信息:

"The model backing the 'AddressBook' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the RecreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data."

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

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”,当我尝试将联系人对象添加到上下文时,会发生错误。我在这里遗漏了什么吗?

最佳答案

现在是:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    Database.SetInitializer<YourDbContext>(null);
    base.OnModelCreating(modelBuilder);
}

在您的 YourDbContext.cs 文件中。

关于.net - 自数据库创建以来,支持 <Database> 上下文的模型已发生更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3600175/

相关文章:

c# - 试图通过反射获得文字

c# - 为什么这个条件返回真?

.net - Visual Studio 2010 .NET Framework 3.5 不可用

c# - 获取错误错误 "Entity ' J' 未定义”

c# - 具有包含和可为空值的 Linq 查询

c# - EF 代码第一次迁移 : recreate database and Seed

orm - 在生产中使用代码优先 (ORM) 更改域模型

c# - 服务层和存储库的职责

.net - EF4 可以使用自定义约定从数据库生成模型

c# - Entity Framework : Remove and Add entities with same key in a single request