Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I implement DTOs in repository pattern with EF? [closed]

In my project I'm using EF Code First approach. I have a repository layer, service layer and presentation layer (ASP.NET MVC). I'm using a dedicated viewmodel for each view.

What I'm confused about is that should my services return entities to the controller for mapping them to the viewmodels, or should I implements DTOs and return them from services?

So the question is when the flow is like "EF -> Repository -> Service -> UI", what will be the data transformation. "Entity -> DTO -> Viewmodel" or "Entity -> Viewmodel"?

It seems like if I use DTOs, they'll kinda repeat entities.

I'm trying to follow best practices.

like image 479
SherleyDev Avatar asked Nov 12 '13 15:11

SherleyDev


1 Answers

Use the DTO approach.

This will help you a lot to keep your application independent from database structure changes.

Mapping the EF entities up into the presentation layer will make any DB changes a pain to maintain. So many places you will need to keep an eye on.

As two examples of the different aproaches: Right now, I am working on a huge project that was originally binding directly to EF entities. This leads to all sorts of complications. There are parts that require extensive code changes for even small DB adjustments. On the other hand, at my home pet project, I was able to change the entire database system 3 times without troubles because I had good abstraction layers in between.

Especially now at the start, where your project architecture ist still clean, the work to implement the DTOs seems to be duplicated. But that may change over time when your several application layer start their own lives.

If you dread the seemingly duplicate work for implementing the DTOs, there are mapping libraries like AutoMapper that can take a lot of that pain away from you.

like image 71
Jens H Avatar answered Sep 27 '22 23:09

Jens H