c# - 使用 AutoMapper,如何在不使用 AfterMap 的情况下从映射的父集合成员获取值到子集合成员?

标签 c# automapper

假设如下:

public class ParentSource
{
    public Guid parentId { get; set; }

    public ICollection<ChildSource> children { get; set; }
}

public class ChildSource
{
    public Guid childId { get; set; }
}

public class ParentDestination
{
    public Guid parentId { get; set; }

    public ICollection<ChildDestination> children { get; set; }
}

public class ChildDestination
{
    public Guid childId { get; set; }
    public Guid parentId { get; set; }
    public ParentDestination parent;
}

如何使用 AutoMapper 在不使用 .AfterMap 的情况下使用父级信息填充 ChildDestination 对象?

最佳答案

我认为通过引用成员集合的父实例来填充集合中的子对象而不使用 .AfterMap() 的唯一方法是定制的TypeConverter<TSource, TDestination> .

class Program
{
    static void Main(string[] args)
    {
        AutoMapper.Mapper.CreateMap<ParentSource, ParentDestination>().ConvertUsing<CustomTypeConverter>();

        ParentSource ps = new ParentSource() { parentId = Guid.NewGuid() };
        for (int i = 0; i < 3; i++)
        {
            ps.children.Add(new ChildSource() { childId = Guid.NewGuid() });
        }

        var mappedObject = AutoMapper.Mapper.Map<ParentDestination>(ps);

    }
}

public class ParentSource
{
    public ParentSource()
    {
        children = new HashSet<ChildSource>();
    }

    public Guid parentId { get; set; }
    public ICollection<ChildSource> children { get; set; }
}

public class ChildSource
{
    public Guid childId { get; set; }
}

public class ParentDestination
{
    public ParentDestination()
    {
        children = new HashSet<ChildDestination>();
    }
    public Guid parentId { get; set; }
    public ICollection<ChildDestination> children { get; set; }
}

public class ChildDestination
{
    public Guid childId { get; set; }
    public Guid parentId { get; set; }
    public ParentDestination parent { get; set; }
}

public class CustomTypeConverter : AutoMapper.TypeConverter<ParentSource, ParentDestination>
{
    protected override ParentDestination ConvertCore(ParentSource source)
    {
        var result = new ParentDestination() { parentId = source.parentId };
        result.children = source.children.Select(c => new ChildDestination() { childId = c.childId, parentId = source.parentId, parent = result }).ToList();
        return result;
    }
}

或者您可以使用.AfterMap() 。 :)

关于c# - 使用 AutoMapper,如何在不使用 AfterMap 的情况下从映射的父集合成员获取值到子集合成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8948991/

相关文章:

c# - C# WPF 中的内存泄漏

c# - 是否可以使用 AutoMapper 自动映射除一些复杂属性之外的所有属性?

c# - 将嵌套类转换为字典

c# - 如何将图像列表添加到 WPF ListView ?

c# - 为什么它总是一个空值?

c# - 列表场景的 AutoMapper 似乎只重复映射列表中的第一个对象

c# - 使用 asp.net 样板和 Automapper 进行自定义映射

asp.net-mvc - 尝试将 AutoMapper 添加到 Asp.net Core 2?

c# - AutoMapper 定义映射级别

.net - 为什么 AutoMapper v3 不能工作,因为它正在寻找 v2.2.1.0?