Laz*_*tIT 1 c# typeconverter automapper
我有3个实体:Obj1,Obj2,Obj3
如何使用automapper将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;
}
}
Run Code Online (Sandbox Code Playgroud)
用法简单:
var personViewModel = EntityMapper.Map<PersonViewModel>(person, address, comment);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1772 次 |
| 最近记录: |