错误信息:
“自数据库创建以来,支持‘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”,当我试图将联系人对象添加到上下文时发生错误。我遗漏了什么吗?
这很奇怪,但这里所有的答案对我来说都没用。
对于我来说,有效的初始化器
MigrateDatabaseToLatestVersion
以下是我的解决方案(我知道,它可以简单得多,但这就是我使用它的方式):
class MyDbMigrateToLatest : MigrateDatabaseToLatestVersion<MyDbContext, Configuration>
{
}
public class MyDbContext: DbContext
{
public MyDbContext() : base("DbName")
{
SetInitializer();
}
public MyDbContext(string connString) : base(connString)
{
SetInitializer();
}
private static void SetInitializer()
{
if (ConfigurationManager.AppSettings["RebuildDatabaseOnStart"] == "true")
Database.SetInitializer(new MyDbInitializerForTesting());
else
Database.SetInitializer(new MyDbMigrateToLatest());
}
}
public sealed class Configuration : DbMigrationsConfiguration<MyDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(MyDbContext context)
{
// Whatever
}
}
MyDbInitializerForTesting只是继承自DropCreateDatabaseAlways,所以在某些特定的情况下(测试),整个数据库被重建。否则,它已迁移到最新版本。
我的来源:https://msdn.microsoft.com/en-us/data/jj591621.aspx#specific
创建自定义上下文初始化项:
public class MyDbContextInitializer : MigrateDatabaseToLatestVersion<MyDbContext, Migrations.Configuration>
{
public override void InitializeDatabase(MyDbContext context)
{
bool exists = context.Database.Exists();
base.InitializeDatabase(context);
if (!exists)
{
MyDbSeed.Seed(context);
}
}
}
注意迁移。Configuration是Package Manager Console中由迁移命令行生成的类。您可能需要将迁移的内部修饰符更改为公共修饰符。配置类。
并从您的OmModelCreating注册它:
public partial class MyDbContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer<MyDbContext>(new MyDbContextInitializer());
//other code for creating model
}
}