1. 程式人生 > >序列化型別的物件時檢測到迴圈引用

序列化型別的物件時檢測到迴圈引用

 問題程式碼
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的獨立性,不直接依賴與資料庫實體。