Search code examples
wcfentity-framework-4.1datacontract

Is it possible to use entities as data contracts?


Is it possible to use objects of Entity classes as Data Contract on WCF service ? So I can send them on the client side. is this good design approach ?

I want to my entity classes to be used as DTOs too, so I can send the data retrieved from database to the client.


Solution

  • Yes it is. If you use EntityObject based entities both default code generator and T4 template should mark them with DataContract and DataMember attributes. If you use POCOs you will have to either modify template to generate these attributes for you or create POCOs manually.

    The reason why you need to use those attributes is problem with circular reference. By default EF creates navigation properties on both sides of relation. During serialization, framework needs some hint to know about that circular reference otherwise it will go to infinite loop. To avoid that the entity must be marked with [DataContract(IsReference=true)] and once you use DataContract attribute you must use DataMember to mark each serialized property.

    It is also important to turn off lazy loading because otherwise serialization will trigger lazy loading on every navigation property and it will do this recursively on all lazily loaded entities. So instead of single object you can return from your service all its relations, all their relations, etc.