subash
subash

Reputation: 4137

what is the use of [Datacontract] attribute in entity class of WCF

I am using .net 4.0 and wcf service. I have business entity classes which is not defined with [Datacontract] attribute.

When I try to retrieve less than 1000 records of type business entity class it works fine but when I try retrieving more than 1000 records of type business entity class, it throws this exception:

The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://tempuri.org/:Securities. The InnerException message was 'Maximum number of items that can be serialized or deserialized in an object graph is '65536'. Change the object graph or increase the MaxItemsInObjectGraph quota. '. Please see InnerException for more details.

The problem got solved, when using the [DataContract] attribute defined for the business entity class.

  1. so what importance does the [DataContract] attribute play in the above case?
  2. what is the difference between using a business entity class defined with [DataContract] attribute and without [DataContract] attribute?

Upvotes: 1

Views: 2656

Answers (1)

StuartLC
StuartLC

Reputation: 107237

By applying [DataContract] to a class, you are telling WCF that you will be explicitly declaring which properties are to be serialized by the DataContractSerializer.

By default, without [DataContract], DCS will serialize all public properties, e.g. given the below, if you serialize an instance of House, Window and Door will also be fully serialized.

public class Window
{
  public string Colour {get; set;}
  public bool IsClean {get; set; }
}


public class Door
{
  public string Colour {get; set;}
  public bool IsOpen {get; set; }
}


public class House
{
  public Door Door {get; set;}
  public Window Window {get; set; }
}

By Comparison, if you specify [DataContract] on House, then only members with the [DataMember] attribute will be serialized, viz in the case below, only the Address property of House will be serialized:

[DataContract]
public class House
{
  [DataMember]
  public string Address {get; set;}

  // Omitted DataMember!
  public Door Door {get; set;}
  public Window Window {get; set; }
}

I'm guessing the reason why adding [DataContract] works in your case is probably because you've add it to the root entity, but somewhere down the entity graph "chain", one or more of the composited entities don't have the [DataMember] attribute. If you've just marked your root entity as [DataContract] with no [DataMember]s then only the root entity is serialized, thus avoiding the MaxItemsInGraph setting (but your clients obviously won't receive any of the unserialized entities).

Upvotes: 7

Related Questions