7

I've been looking at a lot of WCF examples using EntityFramework and most of them seem to return some kind of POCO or DTO class to the client.

I was wondering why this was since the default EntityObject includes the [DataContract] attributes and implements INotifyPropertyChanged. Is returning a DTO or POCO class better than an EntityObject (or vise versa)? And is there specific instances where it is better to use one return value over another?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Rachel
  • 130,264
  • 66
  • 304
  • 490
  • 1
    possible duplicate of [WCF, Entity Framework & Data Contracts](http://stackoverflow.com/questions/1121877/wcf-entity-framework-data-contracts) – John Saunders Jan 28 '11 at 05:09

2 Answers2

8

As a best practice, you should definitely have it return a DTO/POCO class that is explicitly designed as a data contract and has no persistence logic.

The reason is, if you pass an EntityObject, you are making an assumption that the consumer of the service will have a reference to the same data context, and this violates the SOA tenet of explicit boundaries. It reduces the reusability of your service.

It is probable that Microsoft implemented DataContract on the EntityObject to support some of their WCF-based database access tools like RIA. The INotifyPropertyChanged is for WPF binding support, and is not related to WCF or data contracts.

Guy Starbuck
  • 21,603
  • 7
  • 53
  • 64
  • Thanks. Is is usual to cast the DTO back into the EntityObject on the Client, or is it preferred to make a new Model for the client's purposes? – Rachel Jan 28 '11 at 13:53
  • Obviously this depends on your architecture, but if the client has a local copy of the database, you can convert the DTO back to the EntityObject. The point is to keep the contract clean so the service doesn't imply any specific implementation, it just provides the data in a vanilla format. – Guy Starbuck Jan 28 '11 at 14:18
  • The client should just work with DTOs which is the type provided by the service it consumes and is more simple of course. Unless you have the need to use the context on the client with all the entities features for some reason (which I doubt because it is a client right?). – kzfabi Nov 28 '12 at 12:57
  • 1
    BTW: I recommend using [EntitiesToDTOs](http://entitiestodtos.codeplex.com) to automatically generated DTOs and Assemblers from your Entity Framework EDMX file. DRY! – kzfabi Nov 28 '12 at 12:59
0

It is worth to return the POCO in some cases where you don't aware of persistence logic. I mean the same POCO can plugged to other ORM or for other purpose. Ok this is advantage of POCO over ORM but it also gives you performance boost over EntityObject which does add proxy/notifiers run time.

Returning POCO - You have to manually update the state of entity when received from WCF.

Returning EntityObject - You receive the entity with maintained state.

indiPy
  • 7,844
  • 3
  • 28
  • 39