我使用实体框架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序列化。
任何人都能够帮助吗?
:)
嗨@laurvasile,是的,这是我使用的方法也是“解决方法”。尽管它并不是完全动态的,但我对此并不满意......对Model的任何更改都需要反映到此手动JSON转换中。我认为如果你可以将一个字段/属性/引用作为LINQ查询的一部分来排除,效率会更高,类似于INCLUDE函数。 – 2010-12-24 00:42:42
被接受为答案(尽管它实际上是一种“解决方法”imho) – 2011-01-10 08:38:51