We have a UserRepository repository that reads data from the database using the EntityFramework and the EntityFramework service class that accesses the repository. And our UI is already accessing this service.

Let's say domain model

 class User { string Name {get; set; }} 

How to give data? Really in the form of domain models?

Options come to mind:

  1. Make another class UserModel (UserDto?) , In which I will have only the required fields, and in the repository method (or in the service) convert the domain model (by simply copying the field values). As an option not to copy data, UserModel may be a descendant of User (what difficulties will it cause?)

  2. Give the domain model, but first detach it from the context.

  • in my application, I act on the first point, for conversions to dto and back I use AutoMapper - Bald
  • @Bald how about AutoMapper performance? Is not it easier to handle pens? Moreover, Dto does not have to be an exact copy of the model. - GreenBee
  • I won’t say about performance, didn’t test everything, I use some handles for some models, but I give simple ones to the automapper . I use entity-framewwork and with the help of navigation properties I do the following: for example, Request has a Type navigation property, so I created a property in dto : TypeName automapper will write the value of the Name property into it. - Bald

1 answer 1

The entities of the domain model are needed to work with them throughout the application as with meaningful units of information. DTO is used when the data you are transmitting is not reflected in the domain. There is no need to produce two classes for each entity.

In the Entity Framework, when retrieving objects from the context, it is possible to declare them untraceable.

 var users = await Context.Users.AsNoTracking().ToListAsync(); 
  • one
    But in this case we get the dependence of the contracts of the service layer on the data storage model. When using a separate set of classes for EF, I can store data in a more convenient form (theoretically). Although this will create the need to maintain the relevance of the model in two places. - GreenBee