我有 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