[英]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.