【发布时间】:2015-07-30 20:53:54
【问题描述】:
我有Test 实体和User 实体。
测试:
public class Test
{
public int Id {get; set;}
public string Title {get; set;}
...
public virtual IList<User> Users {get; set;}
}
用户:
public class User
{
public int Id {get; set;}
public string Name {get; set;}
...
public virtual IList<Test> Tests {get; set;}
}
在我的TestsApiController 中,我有以下操作:
public IQueryable<Test> GetTests()
{
return db.Tests;
}
这会返回一个序列化异常,因为它尝试循环序列化 User 对象,然后是它们的 Test 对象,然后是它们的 User 对象,依此类推。
我目前的计划是创建一个TestDTO,其中包含一个IList<int> UserIds,而不是实际的对象。然后我必须在序列化之前将所有Test 对象转换为TestDTO 对象,这有点烦人。然后,如果我想序列化具有循环依赖关系的其他实体,我将不得不为它们创建更多的数据传输对象。
有没有办法创建或配置序列化程序以自动序列化此上下文中的 User(或任何其他)对象以简化其 Id 属性?
编辑例外:
无论使用XML 还是JSON,我都会遇到同样的异常
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace/>
<InnerException>
<Message>An error has occurred.</Message>
<ExceptionMessage>
Type 'System.Data.Entity.DynamicProxies.Test_6585C5F85A384907958ABA03B661933EF718BDEDE1513392E060DE06E80DB552' with data contract name 'Test_6585C5F85A384907958ABA03B661933EF718BDEDE1513392E060DE06E80DB552:http://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.
</ExceptionMessage>
<ExceptionType>
System.Runtime.Serialization.SerializationException
</ExceptionType>
<StackTrace>...</StackTrace>
</InnerException>
</Error>
【问题讨论】:
-
我想说这里的问题是设计,而不是序列化程序。考虑
Tests 是否真的需要Users 的列表。如果是这样,我会存储一个 ID 列表而不是实际对象。 -
这都是使用实体框架。它存储
User对象而不是它们的Ids 这一事实在我的应用程序的其他地方非常有用。
标签: c# asp.net serialization