我应该用EF在仓库模式中实现DTO吗? [英] Should I implement DTOs in repository pattern with EF?

查看:131
本文介绍了我应该用EF在仓库模式中实现DTO吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,我使用EF Code First方法。我有一个存储库层,服务层和表示层(ASP.NET MVC)。我正在为每个视图使用一个专用的viewmodel。



我很困惑的是,如果我的服务将实体返回给控制器,将其映射到视图模型,或我应该实现DTO并从服务返回吗?



所以问题是当流程如EF - > Repository - > Service - > UI数据转换。 实体 - > DTO - > Viewmodel或Entity - > Viewmodel?



看起来像我使用DTO,他们会重复实体。 >

我试图遵循最佳做法。



谢谢。

解决方案

使用DTO方法。



这将有助于保持应用程序独立于数据库结构更改。



将EF实体映射到表示层将使任何数据库更改变得难以维护。许多地方你需要关注。



作为不同aproache的两个例子:现在,我正在开发一个最初绑定的巨大项目到EF实体。这导致各种并发症。有些零件需要大量代码更改,甚至可以进行小型DB调整。另一方面,在我的家庭宠物项目中,我能够改变整个数据库系统3次,没有麻烦,因为我之间有很好的抽象层。



特别是现在在一开始,您的项目架构仍然很干净,实施DTO的工作似乎是重复的。但是,当您的几个应用层开始自己的生活时,可能会随时间而变化。



如果您对实现DTO的似乎重复的工作感到恐惧,则会出现一些映射库,如 AutoMapper ,可以让你的痛苦远离。


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.

Thank you.

解决方案

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.

这篇关于我应该用EF在仓库模式中实现DTO吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆