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);

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()); 
            } 
        } 
    }
View Code
public class BaseController : Controller
    {
        protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior) 
        { 
            return new MyJsonResult 
            { 
                Data = data, 
                ContentType = contentType, 
                ContentEncoding = contentEncoding, 
                JsonRequestBehavior = behavior }; 
        }

    }
View Code

 当成,自己组合匿名对象也是可以的,比如来自SO的一个代码片段:

http://stackoverflow.com/questions/16949520/circular-reference-detected-exception-while-serializing-object-to-json

The solution:

Return the data (properties) you need as anonymous objects.

A code example:

In this case I needed the 3 latest tickets, based on "Date Scheduled". But also needed several properties stored in related entities.

var tickets =
     context.TicketDetails
    .Where(t => t.DateScheduled >= DateTime.Now)
    .OrderBy(t => t.DateScheduled)
    .Take(3)
    .Include(t => t.Ticket)
    .Include(t => t.Ticket.Feature)
    .Include(t => t.Ticket.Feature.Property)
    .AsEnumerable()
    .Select(
        t =>
        new {
            ID = t.Ticket.ID,
            Address = t.Ticket.Feature.Property.Address,
            Subject = t.Ticket.Subject,
            DateScheduled = String.Format("{0:MMMM dd, yyyy}", t.DateScheduled)
    }
);
同样是在那篇帖子里面有回复AsNoTracking可以的,不过我测试的结果是不行,也许是6.1.3的版本和之前5.X的在这方面有区别?

规避json序列化的时候直接序列化该t_saleform对象,改为序列化其它没有这种映射关系的对象。代码如下:
   1: public JsonResult GetSaleByNo(string id)
   2: {
   3:     SaleMvcUI.Helper.saleDBEntities saleDB = new Helper.saleDBEntities();
   4:  
   5:     var saleF = (from sf in saleDB.t_saleform
   6:                  where sf.f_saleform_no == id
   7:                  select new
   8:                  {
   9:                      f_saleform_no = sf.f_saleform_no,
  10:                      f_saleform_date = sf.f_saleform_date,
  11:                      f_customer = sf.f_customer,
  12:                      f_sales = sf.f_sales,
  13:                      f_remark = sf.f_remark
  14:                  }).First();
  15:     //此处为了好转换日期格式,多定义了一个临时变量。
  16:     var tm = new{
  17:                      f_saleform_no = saleF.f_saleform_no,
  18:                      f_saleform_date = saleF.f_saleform_date.ToString("yyyy-MM-dd"),
  19:                      f_customer = saleF.f_customer,
  20:                      f_sales = saleF.f_sales,
  21:                      f_remark = saleF.f_remark
  22:                  };
  23:     return this.Json(tm, JsonRequestBehavior.AllowGet);
  24: }
 

posted on 2016-05-03 11:38  sPhinX  阅读(545)  评论(0编辑  收藏  举报

导航