EF问题集合

1. 在使用数据迁移的过程中,如果手工删除了本地数据库之后,再次尝试连接被删除的数据库,会有以下提示:

System.Data.SqlClient.SqlException (0x80131904): Cannot open database "ContosoUniversity3" requested by the login. The login failed.

修复方法:打开SQL Server Management Studio,连接上被删除数据库所在的引擎(一般是LocalDB),在Tool中再删除一次显示在列表中的数据库,会提示无法删除,文件不存在等等过,

不必管它,断开连接,再次连接,可以看到数据库已经不在列表当中,现在数据迁移可以再次使用被删除的数据库名

如果没有SSMS,可以执行‘sqllocaldb.exe stop v11.0’和‘sqllocaldb.exe delete v11.0’(未实测),以上知识来自下面的提问:

http://stackoverflow.com/questions/21592062/ef6-migrations-localdb-update-database-login-failed

http://stackoverflow.com/questions/13275054/ef5-cannot-attach-the-file-0-as-database-1/16339164#16339164

 

2. 使用数据迁移的流程:

来自:http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/migrations-and-deployment-with-the-entity-framework-in-an-asp-net-mvc-application

注释掉Web.Config当中的数据初始化器的代码

修改连接字符串,使用新数据库

执行enable-migrations

执行add-migration XXXXXX(为迁移生成快照,同时生成迁移用的文件,可以修改生成的文件)

执行update-database(更新改动到数据库当中)

 

3. 使用代码执行迁移,查看迁移生成的代码

https://romiller.com/2012/02/09/running-scripting-migrations-from-code/

var configuration = new Configuration();
var migrator = new DbMigrator(configuration);
migrator.Update();

var configuration = new Configuration();
var migrator = new DbMigrator(configuration);
var scriptor = new MigratorScriptingDecorator(migrator);
string script = scriptor.ScriptUpdate(sourceMigration: null, targetMigration: null);

你可能感兴趣的:(EF问题集合)