您的位置:首页 > 其它

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

2017-06-02 12:11 525 查看
 问题代码
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_08FCB4D1A67AD4A15169A1228CF2AE9BD99F78546715A
4000
4E4AF5E8E73F3A36322'.

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的独立性,不直接依赖与数据库实体。 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mvc 序列化
相关文章推荐