2010-12-14 72 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