gpt4 book ai didi

c# - Automapper - 如何使用 automapper 将三个实体映射到一个实体?

转载 作者:太空宇宙 更新时间:2023-11-03 18:37:16 24 4
gpt4 key购买 nike

我有 3 个实体:Obj1Obj2Obj3

如何使用自动映射器将 3 个实体映射到一个实体?

最佳答案

This post描述了如何使用以下辅助类将多个对象映射到单个新对象:

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);

关于c# - Automapper - 如何使用 automapper 将三个实体映射到一个实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13523408/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com