[英]Automapper - How to map three entity to one with automapper?
我有3個實體: Obj1
, Obj2
, Obj3
如何使用自動映射器將3個實體映射到一個實體?
這篇文章介紹了如何使用以下幫助程序類將多個對象映射到單個新對象中:
public static class EntityMapper
{
public static T Map<T>(params object[] sources) where T : class
{
if (!sources.Any())
{
return default(T);
}
var initialSource = sources[0];
var mappingResult = Map<T>(initialSource);
// Now map the remaining source objects
if (sources.Count() > 1)
{
Map(mappingResult, sources.Skip(1).ToArray());
}
return mappingResult;
}
private static void Map(object destination, params object[] sources)
{
if (!sources.Any())
{
return;
}
var destinationType = destination.GetType();
foreach (var source in sources)
{
var sourceType = source.GetType();
Mapper.Map(source, destination, sourceType, destinationType);
}
}
private static T Map<T>(object source) where T : class
{
var destinationType = typeof(T)
var sourceType = source.GetType();
var mappingResult = Mapper.Map(source, sourceType, destinationType);
return mappingResult as T;
}
}
簡單用法:
var personViewModel = EntityMapper.Map<PersonViewModel>(person, address, comment);
假設需要將它們映射到Obj0
。 基本上,您需要一個一個地映射它們。
Mapper.Map(Obj1, Obj0);
Mapper.Map(Obj2, Obj0);
Mapper.Map(Obj3, Obj0);
在更高級的方案中,您可以將類型組成一些CompositeObj
並在Obj0
和CompositeObj
之間創建映射。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.