【发布时间】:2015-05-21 13:55:20
【问题描述】:
我在实体框架中有以下模型:
public class Customer
{
[XmlIgnore]
public virtual ICollection<Customer> Children { get; set; }
public string Name { get; set; }
}
现在我尝试使用 web api 对其进行序列化:
public class CustomerController:ApiController {
public HttpResponseMessage GetAll()
{
using (var tc = new DataContext())
{
List<Customer> allCustomers = tc.Customers.ToList();
return Request.CreateResponse(HttpStatusCode.OK, allCustomers);
}
}
}
当我这样做并使用 POST 调用该方法时 我收到以下错误:
“ObjectContent`1”类型未能序列化响应正文 内容类型'应用程序/json;字符集=utf-8
InnerException:“错误 从“儿童”中获得价值 'System.Data.Entity.DynamicProxies.Customer"
InnerException(2):“ ObjectContext 实例已被释放,不能再用于 需要连接的操作。”
customers.Children 当前是一个空列表。
我猜这个问题的发生是因为 Children 与 Customer 的类型相同,导致“无限序列化循环”。 (我没有更好的词来形容)
我已经尝试过 XmlIgnore 来阻止该属性被序列化,但没有效果。
【问题讨论】:
标签: c# json entity-framework serialization asp.net-web-api