Entity Framework and DTO

dotnetlinc picture dotnetlinc · May 6, 2011 · Viewed 26.9k times · Source

Im planning to use the Entities generated by the EF (POCO) in sending data to the client instead of creating DTOs? Is this a good practice? Basically, my EDMX file is on my DAL layer. So the UI will have direct access on my DAL. Thanks.

Answer

Marc Gravell picture Marc Gravell · May 6, 2011

It depends on how close the client is to your object domain. If it is your client, then maybe - and indeed this is pretty much how ADO.NET Data Services (etc) work - directly exposing your model.

However, if the client is anything else I would suggest a dedicated DTO. In fact, I'd suggest it anyway ;p Otherwise, it gets somewhat complex:

  • controlling the serialization details (what members? what names? what happens when we version it?)
  • handling relation properties (it has an Orders member... but is that lazily loaded? do we want that?)
  • merging incoming objects (for updates etc) back into the model
  • suppressing any logic that you've added in setters, etc, during deserialization
  • handling identity management if you get 2 separate copies of the same object back in a tree-based serializer like DataContractSerializer

In most cases, having a separate DTO makes most of these problems just go away