1

我有一个使用 Entity Framework 4 的 MVC-3 (RC1) 应用程序。

我希望从控制器操作返回一个 JSON 对象。这个对象被其他对象引用,显然返回引用。

因此,我收到以下循环引用错误:

“/”应用程序中的服务器错误。

序列化“Application.Models.ReferenceObject”类型的对象时检测到循环引用。

说明:执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

异常详细信息:System.InvalidOperationException:在序列化“Application.Models.ReferenceObject”类型的对象时检测到循环引用。

注意:ApplicationReferenceObject显然是实际命名空间/对象的替代品。

根据Stack Overflow: Circular reference exception when serializing LINQ to SQL classes,这可以使用 JSON.Net 来克服;但是我想避免这种情况,而是尝试从被序列化的对象中排除有问题的引用属性。

我是什么意思?

我想做这样的事情:

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

where**<method>**是一些与方法相反的ObjectQuery(Of T).Include方法,并且ObjectsReferencingThis是导致循环引用的属性。

注意:我不希望删除这些属性或创建 POCO,因为这只会影响 Json 序列化。

请问有人可以帮忙吗?

:)

4

2 回答 2

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 对象中:)

于 2010-12-14T06:29:27.537 回答
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

于 2016-09-26T17:40:18.180 回答