I have a Reason object:
public class Reason
{
public virtual long Id { get; set; }
public virtual string Name { get; set; }
public virtual Comp
There are multiple solutions for your problem and they really depend on the type of service you are using and on the type of serialization:
All other approaches are based on tweeking serialization as @Haz suggested:
DataContractSerializer
: explicitly mark your entities with DataContract[IsReference=true]
and all properties with [DataMember]
attributes. This will allow you to use circular references. If you are using T4 template to generate entities you must modify it to add these attributes for you.DataContractSerializer
: implicit serialization. Mark one of related navigation properties with [IgnoreDataMember]
attribute so that property is not serialized.XmlSerializer
: mark one fo related navigation properties with [XmlIgnore]
attribute [NonSerialized]
(+1 for Haz he was the first to mention this) for common serialization or [ScriptIgnore]
for some JSON related serialization.You haven't supplied the definition for your company class.... But I'm guessing you have a collection of Reason as a property.
Lazy loading in an SOA Enviroment doesn't really work. You can't have unlimited lazy navigation over a serialized class, once you leave the webmethod you have no way to call back into the original datacontext from the webmethod consumer to lookup the properites... so the serializer will try and visit all properties, including lazy properties at the time of serialization.
You need to disable serialization on one part of the circular reference, either on the Reason collection in Company class, or the Company in Reason class.
You can use the "NotSerialized" attribute to disable serialization of a particular field.
I usually write specific classes for the webservice. While this is some extra work it has the advantage that the webservice gets more robust as small changes in your entities won't go unoticed and silently fail on the side of the consumer/javascript. For example if I change the name of a property.
There are a few things you can do to reduce the work and one is to use AutoMapper which can automatically map between objects.