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

标签 c# automapper typeconverter

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

相关文章:

c# - asp.net/C# 中的静态变量

c# - 无法写入文件名为 "aux"的任何路径

c# - Winform变得不响应,异步编程,C#

c# - 如何在没有 DI 的情况下将 AutoMapper 9 与静态实现一起使用?

dependency-injection - 使用 ITypeConverter 进行 AutoMapper 依赖注入(inject)

kotlin - 在 session 室数据库中使用 'like'搜索加密的文本

python - 在 Python 中将 str 数据转换为文件对象

c# - 如何验证包含工作表名称的 Excel 单元格引用?

c# - MVC 传递模型与 View 模型 - 如何保留模型元信息?

versioning - AutoMapper 2.0 中的 ITypeConverter 接口(interface)已更改