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

时间:2012-01-20 23:06:09

标签: 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;
}

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

2 个答案:

答案 0 :(得分:1)

正如您在评论中所说,如果您不想使用AfterMap,ForMember将是另一种选择。你可以创建一个ForMember转换器,使用linq,可以很快地遍历源子节点,将它们转换为目标子节点,然后设置Parent属性。

或者您可以使用AfterMap。 :)

<强>更新

也许是这样的(未经测试):

.ForMember(d => d.children, 
    o => o.MapFrom(s => 
        from child in s.children
        select new ChildDestination {
            childId = child.childId,
            parentId = s.parentId,
            parent = s
        }));

答案 1 :(得分:1)

我认为在不使用.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()。 :)