J. Davidson
J. Davidson

Reputation: 3307

Serialization in Entities

Hi i have following entity

Employee
---------
emp_id
report_id
last_name
first_name
----------Navigation Properties
employee1
employee2

It has foreign key relation with same table emp_id and 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>

Spent alot of time on it cant seem to figure out how to shake off this error. Please help. Thanks

Upvotes: 0

Views: 42

Answers (2)

Mohamed.Abdo
Mohamed.Abdo

Reputation: 2200

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

Upvotes: 0

Marco
Marco

Reputation: 23937

You need to add [DataContract(IsReference = true)] to your Employee class.

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

Reference on MSDN

Upvotes: 1

Related Questions