views:

625

answers:

2

I have a framework with objects and data access code. This objects are mapped to the database using NHibernate.

For example my framework has class Customer and Order:

public class Customer
{
      private Guid _id;
      private string _name;
      private IList<Order> _orders;

      public properties...
}


public class Order
{
     private Guid _id;
     private string _orderNumber;

     public properties...
}

I also have a WCF service with a method PersistCustomer. Like so:

[ServiceContract]
public interface ICustomerService
{

      [OperationContract]
      void PersistCustomer(Customer customer);
}

This WCF have a reference to my framework library.

I've created a client app for the WCF service (a simple console app) and it works!

The main thing i couldn't understand: why does it work without decorating my classes in the framework as DataContract and their properties as DataMembers? And should i decorate them?

Thanks

+2  A: 

You don't have to, but you should. Specific contract declarations allow you to control how classes are serialised on the wire, allowing you to hide attributes, reorder the properties in the message, make some properties optional, some mandatory, and control the namespace of the data contract.

If you don't then .NET makes a decent guess at it, but at some point you will need control, for example if you added a new property to a class but wanted older clients to work you would make it as an optional member in the data contract, and the older clients would continue to work.

blowdart
yes, exactly - it *might* work without the attributes, but being **explicit** helps later on in maintenance, especially when someone else takes over. Be explicit - make your life easier! :-)
marc_s
+2  A: 

Your classes serialize just fine due to explicit support added in .NET 3.5 SP1 for plain old C# objects (POCO).

This was likely added for two reasons:

  • Backwards compatibility with ASMX services
  • Simplifies getting started with WCF

A good summary can be found in Aaron Skonnards article DataContracts without attributes (POCO support) in .NET 3.5 SP1.

However, just like @blowdart mentions, you should decorate your DataContracts, which will then force you to use DataMember, so as to be explicit during serialization. Sooner or later you will need to change the DataContract and you will likely need to maintain backwards compatibility with existing clients.

Zach Bonham
POCO stands for Plain Old CLR Objects (as opposed to C# Objects)
Andrei Rinea