C# 实体中的序列化

C# 实体中的序列化,c#,entity-framework,asp.net-web-api,C#,Entity Framework,Asp.net Web Api,嗨,我有以下实体 Employee --------- emp_id report_id last_name first_name ----------Navigation Properties employee1 employee2 它与相同的表emp\u id和报告id具有外键关系 When I run webapi that i created i keep getting error <Message>An error has occurred.</Message

嗨,我有以下实体

Employee
---------
emp_id
report_id
last_name
first_name
----------Navigation Properties
employee1
employee2
它与相同的表emp\u id和报告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>
当我运行我创建的webapi时,我不断地遇到错误
发生了一个错误。
'ObjectContent'1'类型未能序列化内容类型'application/xml'的响应正文;字符集=utf-8'。
System.InvalidOperationException异常
发生了一个错误。
“Cm.Entities.employee”类型的对象图包含循环,如果禁用引用跟踪,则无法序列化。
System.Runtime.Serialization.SerializationException
花了很多时间在它上面,似乎不知道如何摆脱这个错误。请帮忙。
谢谢

您需要将
[DataContract(IsReference=true)]
添加到您的
员工
类中

[DataContract(IsReference = true)] 
[Serializable]
public class Employee
{
   /* ... properties */
}
参考

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