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);
4.EF在转换成JsonResult时遇到无限循环的解决办法
序列化类型为“System.Data.Entity.DynamicProxies.Photos_1F5D250F2735650E782711718DE2EFF2BBEA68EE8F6C5A1CF253FAABD0681F7B”的对象时检测到循环引用。
来自:http://www.cnblogs.com/gmxq/p/4921974.html
干净优雅的好方法
摘抄于下:
public class MyJsonResult : JsonResult { public JsonSerializerSettings Settings { get; private set; } public MyJsonResult() { Settings = new JsonSerializerSettings { //这句是解决问题的关键,也就是json.net官方给出的解决配置选项. ReferenceLoopHandling = ReferenceLoopHandling.Ignore }; } public override void ExecuteResult(ControllerContext context) { if (context == null) throw new ArgumentNullException("context"); if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) throw new InvalidOperationException("JSON GET is not allowed"); HttpResponseBase response = context.HttpContext.Response; response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType; if (this.ContentEncoding != null) response.ContentEncoding = this.ContentEncoding; if (this.Data == null) return; var scriptSerializer = JsonSerializer.Create(this.Settings); using (var sw = new StringWriter()) { scriptSerializer.Serialize(sw, this.Data); response.Write(sw.ToString()); } } }