问题描述
我在Asp.net MVC应用程序中使用Automapper。
我有一个问题关于automapper的使用
I'm using Automapper in Asp.net mvc application.I have a question regard to the usage of automapper
从大量的示例代码中,我看到了人们使用映射器 Mapper.Map<目标>(来源)
直接的行动,我不知道这是否是好prctice,在我的观点,我想换行映射
在代理对象,而不是让它与控制器的通信代码
直接
from lots of sample code, I saw people use mapper Mapper.Map<Target>(source)
directly in action, I'm not sure if this is good prctice, in my point of view, I would like to wrap the Mapper
code in the proxy object instead of let it talk with controller
directly
public BankflowData CreateBankflowAdjustments(BankflowData addedBankFlow)
{
var bankflow = Mapper.Map<Bankflow>(addedBankFlow);
var newBankflow = Underlying.CreateBankFlowAdjustments(bankflow);
return Mapper.Map<BankflowData>(newBankflow);
}
在这个例子中,控制器一无所知类 Bankflow
,一切知道的是DTO BankflowData code>。
in this example, controller know nothing about Class Bankflow
, all it know is the dto BankflowData
.
我想知道这是使用AutoMapper应用程序中的好的做法呢?
I would like to know if this is a good practice for an application using AutoMapper?
推荐答案
如果你在你的应用服务层,最好放置automapper在服务层。在任何情况下尝试使用扩展方法由automapper这样的映射你的对象:
if you have service layer in your application, it's better to place the automapper in service layer. in any case try to use extension method for mapping your object by automapper like this:
public static class Mapping
{
public static BankflowData CreateBankflowAdjustments(this BankflowData addedBankFlow)
{
var bankflow = Mapper.Map<Bankflow>(addedBankFlow);
var newBankflow = Underlying.CreateBankFlowAdjustments(bankflow);
return Mapper.Map<BankflowData>(newBankflow);
}
}
这会让你的代码更易读,将分离你的顾虑。采取获取更多信息。
it will make your code more readable and will separate your concerns. take this for more info
这篇关于我应该在哪里把automapper代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!