首页 > 解决方案 > 使用私有集自动映射目标集合属性

问题描述

public sealed class ParentSource
{
    public string Name { get; }
    public List<ChildSource> Children { get; }

    public ParentSource(string name)
    {
        Name = name;
        Children = new List<ChildSource>();
    }
}

public sealed class ChildSource
{
    public string Name { get; }

    public ChildSource(string name)
    {
        Name = name;
    }
}

public sealed class ParentDestination
{
    public string Name { get; }
    public List<ChildDestination> Children { get; }

    public ParentDestination(string name)
    {
        Name = name;
        Children = new List<ChildDestination>();
    }
}

public sealed class ChildDestination
{
    public string Name { get; }

    public ChildDestination(string name)
    {
        Name = name;
    }
}

据我了解,我需要的只是以下映射:

CreateMap<ParentSource, ParentDestination>();
CreateMap<ChildSource, ChildDestination>();

调用映射:

var parentSource = new ParentSource("parent");
var childSource = new ChildSource("child");
parentSource.Children.Add(childSource);

var parentDestination = mapper.Map<ParentSource, ParentDestination>(parentSource);

除非我将公共设置器添加到 Children 属性,否则目标父级的子集合不包含任何成员。如果没有公共二传手,我怎样才能完成这项工作?

标签: c#automapper

解决方案


推荐阅读