2010-12-14 71 views
1

我使用實體框架4.如何避免循環引用,而序列化實體框架

的MVC-3(RC1)應用程序,我想從一個控制器動作返回一個JSON對象。該對象被其他對象引用,顯然返回引用。

我從而收到以下循環引用錯誤:

Server Error in '/' Application.

A circular reference was detected while serializing an object of type 'Application.Models.ReferenceObject'.

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 'Application.Models.ReferenceObject'.

NB:應用 & ReferenceObject顯然替代實際命名空間/物體。

根據Stack Overflow: Circular reference exception when serializing LINQ to SQL classes,這可以通過使用JSON.Net來克服;但我想避免這種情況,而是嘗試從被序列化的對象中排除有問題的引用屬性。

我的意思是?

我想要做這樣的事情:

IList<ReferenceObject> list = Repository.GetReferenceObjects(); 
return Json(list.**<method>**("ObjectsReferencingThis")); 

其中**<method>**是一些方法,做相反的ObjectQuery(Of T).Include方法和ObjectsReferencingThis是導致循環引用的屬性。

注意:我不想刪除這些屬性或創建POCO,因爲這隻影響Json序列化。

任何人都能夠幫助嗎?

:)

回答

2

我在以前的一個項目中工作時遇到過類似的問題。 這裏是我落得這樣做:

IList<Product> list = Repository.GetProducts(); 
    var collection = products.Select(product => new 
     { 
      id = product.Id, 
      name = product.Name, 
      detailUrl = product.DetailUrl, 
      imageLargeUrl = product.ThumbNailUrl, 
      tagtitle = product.Name.ToUpper(), 
      tagheader = "Words our cherished patrons use to describe this product", 
      tagwords = from tag in product.Tags group tag by tag.Name into words select new { name =   words.Key, weight = words.Count() } 
     }); 

var result = new {id = inquiry.Id, products = collection, }; 
return this.Jsonp(result); 

下面是結果的Json會是什麼樣子:

{ 
"id" : 2, 
"products" : [{ 
    "id" : "3605970008857", 
    "name" : "TITLE1", 
    "detailUrl" : "http://www.urlhere.com", 
    "tagwords" : [{ 
     "name" : "roses", 
     "weight" : 1 
    }, 
    { 
     "name" : "cotton", 
     "weight" : 1 
    }, 
    { 
     "name" : "happy", 
     "weight" : 1 
    }] 
}, 
{ 
    "id" : "3605970019891", 
    "name" : "TITLE2", 
    "detailUrl" : "http://www.urlhere.com", 
    "tagwords" : [] 
}], 

}

您還可以添加從你引用的對象的任何其他屬性結果如你所願,將顯示在你的Json對象:)

+0

嗨@laurvasile,是的,這是我使用的方法也是「解決方法」。儘管它並不是完全動態的,但我對此並不滿意......對Model的任何更改都需要反映到此手動JSON轉換中。我認爲如果你可以將一個字段/屬性/引用作爲LINQ查詢的一部分來排除,效率會更高,類似於INCLUDE函數。 – 2010-12-24 00:42:42

+0

被接受爲答案(儘管它實際上是一種「解決方法」imho) – 2011-01-10 08:38:51

0

我做了一個非常小的解決方案,不建議如果你有很大的列表

letters=UserOperations.GetDepartmentLettersForSecretary(pageNumber, pageSize,(Session["User"] as User).DepartmentID.Value, (Session["User"] as User).ID); 

foreach (Letter letter in letters) 
{ 
    letter.LetterStatus.Letters = null; 
} 

circular reference在我的情況下,問題是LetterStatus.Letters 所以我Iterated through the listassigned it to null

因爲我告訴你它的not recommended如果你very big list