实体中的序列化

时间:2014-03-24 08:25:40

标签: c# entity-framework asp.net-web-api

您好我有以下实体

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>

花了很多时间似乎无法弄清楚如何摆脱这个错误。请帮忙。 谢谢

2 个答案:

答案 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;
}