0

When using Entity Framework code-first for example, is it advisable to use DTO classes inside your view model? Or should you directly use the entity classes?

I currently do it this way to not have to use [NotMapped] attribute and set some calculated properties on my DTO instead.

I guess it also has the benefit of not having to apply validation annotations directly on the entity class.

The reason for this question is if this is the correct way to go. What are your thoughts?

2
  • Aside from Views that are for one-to-one CRUD operations on an entity, they often require models that compose two or more entities, and other things as appropriate. I think you will find you often can't just use entity classes directly. Commented May 31, 2020 at 10:30
  • please see this link : driver733.com/2018/10/08/entity-and-dto.html Commented May 31, 2020 at 11:34

1 Answer 1

1

You're on the right path. Definitely don't use EF models in your ViewModel. It creates a coupling between the database and the UI.

However... Using the dtos in viewmodel are but can cause problems when your UI diverges from the underlying api.

Unless it's a very small application I would tend to have models that I compose to make ViewModels and use something like AutoMapper to transfer the data between the UI model and the DTO.

You can use the same technique on the back end to transfer data bewteen the DTO and the EF model.

This keeps the DTO simple as it only has one job - transferring data at the api level. It neither knows nor cares about the UI or the database.

Sign up to request clarification or add additional context in comments.

2 Comments

Well I'm currently using automapper too. My services return Dto objects that I use in my ViewModels. And the mapping is done using automapper. For example Client -> ClientDto and the other way around if I need to create or update an entity. So this isn't a bad way of doing things?
Nice. This is a good way of doing things, just watch out for the service/ui coupling.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.