您好我有以下实体
Employee
---------
emp_id
report_id
last_name
first_name
----------Navigation Properties
employee1
employee2
它与同一个表emp_id和report_id
具有外键关系When I run webapi that i created i keep getting 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>
Object graph for type 'Cm.Entities.employee' contains cycles and cannot be serialized if reference tracking is disabled.
</ExceptionMessage>
<ExceptionType>
System.Runtime.Serialization.SerializationException
</ExceptionType>
花了很多时间似乎无法弄清楚如何摆脱这个错误。请帮忙。 谢谢
答案 0 :(得分:1)
您需要将[DataContract(IsReference = true)]
添加到Employee
班级。
[DataContract(IsReference = true)]
[Serializable]
public class Employee
{
/* ... properties */
}
参考MSDN
答案 1 :(得分:0)
public static class WebApiConfig
{
//....
public static void Register(HttpConfiguration config)
{ config.Formatters.XmlFormatter.UseXmlSerializer = true;
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling =
Newtonsoft.Json.PreserveReferencesHandling.Objects;
}