Design – Is it good practice to use entity objects as data transfer objects

Architecturedesigndesign-patternsdomain-driven-designentity-framework

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.

Best Answer

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.