问题描述
我已经使用Entity Framework代码优先开发了带有本地sql Server数据库的WPF应用。
用app.config
中的新连接字符串替换旧的连接字符串之后,如何运行所有迁移到新的远程数据库?
我需要使用app.config
中的Entity Framework标签进行任何更改吗?
<entityFramework>
<providers>
<provider invariantName="System.Data.sqlClient"
type="System.Data.Entity.sqlServer.sqlProviderServices,EntityFramework.sqlServer" />
</providers>
</entityFramework>
更清楚地说:我的问题是,现在如果我运行Update-Database
,我希望它运行在新定义的数据库服务器上找不到的所有迁移,这应该是不存在的所有迁移在该新服务器上。相反,我得到的是:
PM> Update-Database
No pending explicit migrations.
所以即使我替换了连接字符串,它仍然会查看旧数据库。
解决方法
我自己找到了问题。我最初声明DbContext类和构造函数的方式如下:
public class MyContext : DbContext
{
public MyContext : base()
{ }
}
显然,EntityFramework会自动从app.config
查找连接字符串。但是,当我更改了该连接字符串时,即使我没有更改其名称,EF本身也没有应用该更改。所以我将构造函数更改为
public MyContext : base("mycn") // unchanged name of the connection string
{ }
然后才应用更改。对我来说有点奇怪,但是...