序列化实体框架类时如何避免循环引用

发布于 2024-10-07 08:14:59 字数 1368 浏览 4 评论 0原文

我有一个使用实体框架 4 的 MVC-3 (RC1) 应用程序。

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

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

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

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

描述:未处理的异常 执行期间发生的 当前的网络请求。请查看 堆栈跟踪以获取有关的更多信息 错误及其起源 代码。

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

注意:申请 & ReferenceObject 显然是实际名称空间/对象的替代品。

根据 堆栈溢出:序列化 LINQ to SQL 类时出现循环引用异常,这可以使用 JSON.Net 来克服;但是我想避免这种情况,而是尝试从正在序列化的对象中排除有问题的引用属性。

我是什么意思?

我想做这样的事情:

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

其中 **** 是一些与 ObjectQuery(Of T).Include 方法和 ObjectsReferencingThis 是导致循环引用的属性。

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

有人可以帮忙吗?

:)

I have an MVC-3 (RC1) application using Entity Framework 4.

I wish to return a JSON object from a controller action. This object is referenced by other objects, which obviously return the reference.

I thus receive the following circular reference error:

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: Application & ReferenceObject are obviously replacements for the actual namespace / object.

According to Stack Overflow: Circular reference exception when serializing LINQ to SQL classes, this can be overcome using JSON.Net; however I would like to avoid this and instead try to exclude the offending reference properties from the object being serialized.

What do I mean?

I want to do something like this:

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

where **<method>** is some method that does the opposite to the ObjectQuery(Of T).Include method and ObjectsReferencingThis is the property that is causing the circular reference.

NB: I do not wish to remove these properties or create POCOs as this only affects the Json serialization.

Anyone able to help please?

:)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

画尸师 2024-10-14 08:15:00

我在从事之前的一个项目时遇到了类似的问题。
这是我最终所做的:

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

I had a similar problem when worked on one of my previous project.
Here is what I ended up doing:

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);

Here is how the result Json would look like:

{
"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" : []
}],

}

You can also add any other properties from you referenced objects to the result as you wish,to be shown in your Json object :)

情丝乱 2024-10-14 08:15:00

我做了一个非常简单的解决方案,如果您有很大的列表,则不建议使用该解决

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;
}

方案,在我的例子中,循环引用的问题位于 LetterStatus.Letters 中
因此,我迭代了列表将其分配为 null

正如我告诉过您的那样,如果您有非常大的列表,则不推荐代码>

I made a very trivial solution which is not recommended if you have very big list

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;
}

the problem of circular reference in my case is in LetterStatus.Letters
so I Iterated through the list and assigned it to null

as I told you its not recommended if you have very big list

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文