【发布时间】:2015-05-18 10:24:04
【问题描述】:
Automapper 多对一转换
如何将源对象中的许多属性的值转换为目标对象中的单一类型? 我可以在这种情况下使用Value Resolvers吗?或者也许有更好的解决方案?
文档
这里是 example 来自 documentation - 一对一的转换
Mapper.CreateMap<Source, Destination>()
.ForMember(dest => dest.Total,
opt => opt.ResolveUsing<CustomResolver>().FromMember(src => src.SubTotal));
Mapper.CreateMap<OtherSource, OtherDest>()
.ForMember(dest => dest.OtherTotal,
opt => opt.ResolveUsing<CustomResolver>().FromMember(src => src.OtherSubTotal));
public class CustomResolver : ValueResolver<decimal, decimal> {
// logic here
}
案例
我想将两个对象合二为一(多对一转换)。例如:
public class Document
{
public int CurrencyId {get; set;}
public int ExchangeRateId {get; set;}
}
public class DocumentDto
{
public Currency Currency {get; set;}
}
public class CurrencyDetails
{
public Currency Currency {get; private set;}
public ExchangeRate ExchangeRate {get; private set;}
public CurrencyDetails(Currency currency, ExchangeRate exchangeRate)
{
Currency = currency;
ExchangeRate = exchangeRate;
}
}
我想实现这样的目标:
public class CurrencyResolver : ValueResolver<int, int, CurrencyDetails>
{
protected override Currency ResolveCore(int currencyId, int exchangeRateId)
{
var currency = new Currency(currencyId); //simplified logic
var exchangeRate = new ExchangeRate(exchangeRateId);
var currencyDetails = new CurrencyDetails(currency, exchangeRate);
return currencyDetails;
}
}
我知道我可以将整个对象作为源对象传递,但对我来说这不是解决方案:
ValueResolver<Document, Currency>
我不能使用完整对象,因为我有很多文档类型,我不想为每个文档创建新的解析器。 在我的情况下,也不允许忽略元素(用于手动转换)。货币转换逻辑必须由 AutoMapper 执行。
转换发生在后台(在主体转换期间)对我来说很重要。
例如:
Document document;
var documentDto = Mapper.Map<DocumentDto>(document); // and in this moment i have proper CurrencyDetails object!
感谢您的建议。
我的解决方案
我想出了两个解决方案,但我不喜欢它们(太脏了)
解决方案 1 - 用接口包装一个类:
public interface ICurrencyHolder
{
int CurrencyId {get; set;}
int ExchangeRateId {get; set;}
}
public class Document : ICurrencyHolder
{
public int CurrencyId {get; set;}
public int ExchangeRateId {get; set;}
}
并使用带有以下参数的解析器:
ValueResolver<ICurrencyHolder, Currency>
解决方案 2 - 作为源元素对象类型并通过反射获取值
ValueResolver<object, Currency>
这太可怕了!
【问题讨论】:
标签: c# mapping converter automapper dto