序列化类型的对象时检测到循环引用

1 篇文章 0 订阅
 问题代码
public ActionResult SelectAllForClasses()
        {
            var lists = db.OEE_Team.ToList();
            var result = new { lists = db.OEE_Team };
            return Json(result, JsonRequestBehavior.AllowGet);
       }


运行后错误信息如下

Server Error in '/' Application.

A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies.BaseUser_08FCB4D1A67AD4A15169A1228CF2AE9BD99F78546715A4E4AF5E8E73F3A36322'.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.InvalidOperationException: A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies.BaseUser_08FCB4D1A67AD4A15169A1228CF2AE9BD99F78546715A4E4AF5E8E73F3A36322'.

Source Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. 
 


 

 解决方案:
public ActionResult SelectAllForClasses()
{

        var list = from tm in db.OEE_Team
                       select new
                       {
                           ID = tm.ID,
                           Name = tm.Name,
                           LeaderUserID = tm.LeaderUserID
                       };
            var lists = from ea in list
                        select new
                        {
                            ID = ea.ID,
                            Name = ea.Name,
                            LeaderUserID = ea.LeaderUserID
                        };
            return Json((lists).ToList(), JsonRequestBehavior.AllowGet); 
}
问题原因:

这两个表有1对多的实体映射关系。在生成的实体模型中,他们是可以通过这个一对多的映射关系查找相互之间的数据的。在上面的第5行代码里面,这只是定义了一个Linq查询语句并且找出第一条数据,这是没有什么问题。在这个过程中,会自动查找与之有映射关系的数据。第9行代码是在MVC里面返回一个json对象的数据,在这个过程中将我们找到的这条数据进行序列化为json对象的一个过程。在这个过程的时候,由于这个对象有映射关系,那么它在序列化t_saleform对象的时候会序列化该对象的属性t_saleform_detail对象,而这个属性t_saleform_detail对象又有属性t_saleform对象对象,依次反复。就导致了这个问题的产生。 

 


原理解释:
这个时候就不能直接序列化了,要重新定义一个实体,把表中的属性都放里面,序列化这个实体即可。 同时这样也符合ViewModel的独立性,不直接依赖与数据库实体。 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

纪寻川

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值