我不明白为什么在运行update-database
命令时会创建另一个数据库,而不是将未决迁移应用到现有数据库。这种情况似乎偶尔发生。这些是我习惯迁移时使用的陡峭:EF创建另一个数据库,而不是将迁移应用到现有数据库
- 将包管理器项目设置为
MySolution.MyProject
; - 运行
update-database
命令。它偶尔创建一个新的数据库与我的上下文全班名称,例如:MySolution.MyProject.MyContext
; - 在SQL Server Management Studio上,我删除了新创建的数据库
MySolution.MyProject.MyContext
; - 再次运行相同的命令
update-database
。然后,EF正确找到我的数据库,其名称为onlyMyContext
并且仅应用待处理的迁移。
最后一步是最初的预期结果。我想了解:为什么这是另一个数据库正在创建? EF在第一次运行时不应该找到正确的名称吗?为什么我第二次运行时运行正常?我一定在做一些非常错误的事情。
这里是我的迁移项目,这是MySolution.MyProject.MyContext
,的app.config文件:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
...
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="MyContext" connectionString="Data Source=.\SQLDEV;Initial Catalog=MyContext;Persist Security Info=True;User ID=my_user;Password=my_password;Pooling=False;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
...
</configuration>
我给数据库用户的所有特权我的机器(SQL用户>服务器角色)上。
这我的文件MyContext.cs:
namespace MySolution.MyProject
{
public class MyContext : DbContext
{
public MyContext()
{
this.Configuration.LazyLoadingEnabled = false;
}
public MyContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{
}
public MyContext(DbConnection existingConnection, bool contextOwnsConnection)
: base(existingConnection, contextOwnsConnection)
{
}
public MyContext(ObjectContext objectContext, bool dbContextOwnsObjectContext)
: base(objectContext, dbContextOwnsObjectContext)
{
}
// ... lots of stuff...
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
base.OnModelCreating(modelBuilder);
}
}
}
我如何能理解/调试/找出发生了什么事是知道的任何建议。
你可以做的一件事是当你更新数据库时使用'-verbose'开关。我总是使用它,因为它让你看看EF实际上在做什么。 – DrewJordan 2015-02-09 14:08:34
@DrewJordan谢谢!这有帮助! – rodrigogq 2015-02-09 15:59:49
好!如果你发现你的问题,你应该回到这里作为回答,帮助其他可能遇到同样问题的人。 – DrewJordan 2015-02-09 16:01:32