Entity Framework对象序列化出错:检测到循环引用

在ASP.NET MVC3中尝试将Entity Framework对象序列化输出,结果出错,代码如下:

public ActionResult Index()
{
    testContext context = new testContext();
    var data = context.People;
    return Json(data, JsonRequestBehavior.AllowGet);
}

错误信息:

引用内容 引用内容
序列化类型为“System.Data.Entity.DynamicProxies.Person_896262438F25FF951FF9F66BD7BE34F10A8A5D962769864829136BF959F99A37”的对象时检测到循环引用。



错误是EF的导航属性导致的,Person对象的Pets属性引用了Person对象导致无限循环,EF下很多问题ToList后通常能解决,但这次不行:

public ActionResult Index()
{
    testContext context = new testContext();
    var data = context.People.ToList();
    return Json(data, JsonRequestBehavior.AllowGet);
}


序列化类型为xxx的对象时检测到循环引用解决方法

方法一:关闭导航功能(不能再使用导航属性)
public ActionResult Index()
{
    testContext context = new testContext();
    context.Configuration.ProxyCreationEnabled = false;
    var data = context.People;
    return Json(data, JsonRequestBehavior.AllowGet);
}

方法二:转为匿名对象
public ActionResult Index()
{
    testContext context = new testContext();
    var data = context.People.Select(item => new { item.Id, item.Name });
    return Json(data, JsonRequestBehavior.AllowGet);
}


评论: 0 | 引用: 0 | 查看次数: 16127
发表评论
登录后再发表评论!