AutoMapper 使用操作来填充目的地

标签 automapper

我需要使用源对象上的公共(public)方法将列表从目标对象映射到源。

例如

public class Destination
{
    private IList<int> List = new List<int>();
    public void Add(int i) { List.Add(i); }
}

public class Source
{
    public int[] List { get; set; }
}

所以在伪伪语言中映射应该是: Mapper.CreateMap 为 Source.List 中的每个项目调用 Source.Add(item)

这可以做到吗?

最佳答案

是的。使用 ConvertUsing 语法:

Mapper.CreateMap<Source, Destination>()
    .ConvertUsing(s =>
                    {
                        var d = new Destination();
                        foreach(var i in s.List)
                        {
                            d.Add(i);
                        }
                        return d;
                    });

关于AutoMapper 使用操作来填充目的地,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5004235/

相关文章:

c# - LINQ 和 AutoMapper

c# - AutoMapper 需要映射成员和构造函数

automapper - 如果目标不为空,自动映射器可以忽略目标/仅更改空字段

entity-framework - 使用 Automapper 实现多对多到 DTO

asp.net-mvc - 测试方法中的 Moq Automapper 服务在映射时返回 null

c# - AutoMapper 从源嵌套集合映射到另一个集合

Automapper 5.0.2 - 缺少类型映射配置或不受支持的映射

c# - 使用 AutoMapper 将对象的属性映射到字符串

C# automapper 嵌套集合

c# - 将依赖注入(inject)与具有构造函数参数的 AutoMapper ValueResolver 结合使用