在序列化实体框架类时,如何避免循环引用 [英] How do I avoid a circular reference while serializing Entity Framework class

查看:162
本文介绍了在序列化实体框架类时,如何避免循环引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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



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




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



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

异常详细信息:
System.InvalidOperationException:检测到
循环引用,而
序列化
' Application.Models.ReferenceObject'。


注意:应用& ReferenceObject 显然是实际命名空间/对象的替换。



根据 Stack Overflow:将LINQ连接到SQL类时的循环引用异常,这可以用JSON.Net来克服;但是我想避免这种情况,而是尝试从被序列化的对象中排除违规引用属性。



我是什么意思?



我想做这样的事情:

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

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



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

任何人都可以帮助吗?



:)

解决方案

当我以前的项目之一工作时,我遇到了类似的问题。
这是我最后做的:

  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 =我们珍惜的顾客用来描述这个产品的话,
tagwords = from标签在product.Tags组标签通过tag.Name到单词中选择新的{name = words.Key,weight = words.Count()}
});

var result = new {id = inquiry.Id,products = collection,};
返回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 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?

:)

解决方案

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

这篇关于在序列化实体框架类时,如何避免循环引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆