I am wondering because if it is, why does Entity Framework not offer logic to create a new object with the same properties to transfer data between layers?

I use the entity objects that I generate with the entity framework.

  • 3
    I think this is a good question but I can't really tell because it's so hard to read I'm not sure how to fix it. Please edit your question. – candied_orange Jun 2 '17 at 19:04
  • 1
    @CandiedOrange +1, and it makes it all the more scary that this got so many upvotes. – guillaume31 Feb 20 at 13:35

It is up to you.

Most people will tell you that it's not a good practice but you can get away with it in some cases.

EF never played nicely with DDD for multiple reasons, but two stand out: you can't have parameterized constructors on your entities and you can't encapsulate collections. DDD relies on that, since the domain model should include both data and behavior.

In a way, EF forces you to have an anemic domain model and in this case you can use the entities as DTOs. You may run into some issues if you use navigation properties but you can serialize those entities and send them over the wire. It may not be practical though. You will have to control the serialization for each entity that has properties you don't need to send over. The easier way is to simply design separate classes tailored for data transfer. Libraries like AutoMapper are created for this purpose.

For example: Suppose you have a class called Person with the following definition:

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime DateOfBirth { get; get; }

    // plus a bunch of other properties relevant about a person
}

Assuming you want to display a list of employees somewhere, it may be practical to send just the Id, FirstName and LastName. But you'll have to send over all the other irrelevant properties. It's not that big of an issue if you don't care about the size of the response but the general idea is to send just the relevant data. On the other hand, you might design an API that returns a list of persons and in that case sending all properties might be needed, thus making sense to serialize and send the entities. In this case, creating a DTO class is debatable. Some people like mixing up entities and DTOs, some people don't.

To answer your updated question, EF is an ORM. Its job is to map database records to objects and vice versa. What you do with those objects before and after passing through EF is not part of its concerns. Nor should it be.

  • 1
    Briefly summarised. What are the differences between DTOs and POCOs? Don't they just hold data? – Laiv Jun 3 '17 at 11:27
  • 1
    @guillaume31 You can't have a true domain model without taking persistence into consideration. What good is a public interface if I'm forced to use reflection (not to mention other sorts of hacks, provided that my public property is backed by a private field named differently) for loading my aggregates in a valid state? If EF is not providing me with an infrastructure for hidrating my aggregates by using their public interface then I'm better off keeping my business logic elsewhere and have my domain anemic instead of writing additional boiler plate for loading them from the database. – devnull Feb 20 at 15:22
  • 1
    So you'd rather make your entire domain model anemic than name your public collection getter the same way as the private field? (let's set the constructor problem aside, because it is most often against the domain in the first place to expose a constructor taking all of the object's fields...) – guillaume31 Feb 20 at 15:39
  • 1
    @Konrad from here: As of EF Core 2.1, only services known by EF Core can be injected. Support for injecting application services is being considered for a future release. I very much like to have application services injected into my entities. – devnull Jun 6 at 10:44
  • 1
    @Konrad I'd stop using my domain entities as DTOs (if I were to use them in this way). DTOs are useful regardless of EF's support for service injection. – devnull Jun 6 at 11:00

No, it is not.

Ideally, DTOs will match your persistence repositories (aka, your database tables).

But your business classes are not necessarily a match. You might need additional classes , or separated, or joined classes to what you have in database. If your application is small, you might not really see this kind of problems, but in medium to large applications, this will happen often.

Another thing is that DTOs are part of the domain of whatever it is that deals with persistence, while your Business Layer should know nothing about them.

  • A Command object is a DTO that the business layer should know something about. – devnull Jun 2 '17 at 19:55
  • I'm thinking the business layer will probably call the command object indirectly, through an interface. And I mean DTOs as in the simple objects that carry data, with no functionality at all. I am not sure if a command object is a DTO (martinfowler.com/eaaCatalog/dataTransferObject.html). – Juan Carlos Eduardo Romaina Ac Jun 2 '17 at 20:17
  • 1
    Usually, commands are separated into the actual command and its handler. The command contains the data, the handler contains the behavior. When used like this, the command part only contains data received from the client and acts as a DTO between the client and the business layer. – devnull Jun 2 '17 at 20:24
  • DTO don't flow from persistence to domain, they could also come from the outside as in comming data (think in REST APIs). As pointed by devnull, commands and events are somewhat DTOs and they are transfered to the business layer. If handlers are business layer or not depends on the design. – Laiv Jun 2 '17 at 21:18

It is actually a very bad idea. Martin Fowler has an article about Local DTOs.

Long story short, DTO Pattern was used for transfering data outside the process, for example over the wire and not between layers inside the same process.

No, it's a bad practice.

Some reasons:

  1. New entity fields will be in the Dto, by default. Of course, you can ignore using some annotations to not transfer the field (like @JsonIgnore from Java world), but this leads to the next problem...
  2. Lots of annotations/conditions on entity. You need to control what you would like to send on Dto, when some attribute name changed (this will break the contract), add some attribute that is not from the entity, the order of the attributes, etc. Soon you will see your simple entity with a lot of annotations, extra fields and each time will be harder to understand what's happening.
  3. Less flexibility. With a Dto you are free to break the information in more classes, change the attribute names, add new attributes, etc. You can't do this so easy with a entity as Dto.
  4. Not optimized. Your entity will be always bigger than a simple Dto. So you always will have more information to be ignored/serialized and probably more unnecessary information being transmitted.

So, it's easier and safe use some kind of mapper tool to help you on this job, mapping the entity fields to a Dto.

It depends on your project, but most of the time it will be better to have separate DTO.

See this question on Stackoverflow: DTO and Entity in one object? There is a lot of good information there.

To complete what Dherik said, the main problems of using entity objects as data transfer objects are :

1- In a transaction, you take the risk to commit changes made on your entity because you use it as a dto (even if you can detach the entity of the session in a transaction, most of the time you'll need to check this state before any modification on your entity-dto and assure that you are not in a transaction or that the session has been closed if you don't want the modifications to be persisted).

2- The size of datas you share between the client and the server : sometimes you don't want to send all the content of an entity to the client to minimize the size of the request's response. The fact to separate the dto from the entity is flexible to specialize the datas that you want to send in certain usecases or not.

3- Lisibility and maintenance : You have to manage your jpa/hibernate annotations on your entity's fields and maintain the jackson annotations to serialize in json at the same place (even if you can separate them from the entity implementation in putting them in the interface inherited by the entity). Then, if you change your dto content in adding a new field, another person can probably think that it's a field of the entity, therefore a field of the table concerned in your database (even if you can use the @Transient annotation on all your dto fields for the case ..!). In my opinion, it creates noise when you read the entity, but my opinion is surely subjective.

(sorry for the block !)

protected by gnat Sep 21 at 9:59

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.