繁体   English   中英

将枚举映射到具有相同枚举类型的属性的 class

[英]Mapping an enumeration to class with a property of the same enumeration type

假设我有一个 class ,其定义如下:

public class DestinationOuter
{
    public string Name { get; set; }
    public int Age { get; set; }
    public List<DestinationInner> Siblings { get; set; }
}

public class DestinationInner
{
    public string Name { get; set; }
    public RelationEnum Relation { get; set; }
}

并说我有一个源类型:

public class SourceSiblings
{
    public string Name { get; set; }
    public RelationEnum Relation { get; set; }
}

使用 AutoMapper,我可以轻松地创建从SourceSiblings映射到DestinationInner的配置,这样我就可以进行如下映射:

SourceSiblings[] brothers = { ... };
DestinationOuter dest = new DestinationOuter();

Mapper.Map(brothers, dest.Siblings);

但我想做的是 map 直接从SourceSiblingsDestinationOuter 在这种情况下,映射中将忽略DestinationOuter中的 Name 和 Age 属性,但想法是SourceSiblings将映射到DestinationOuter.Siblings 使用上面的 object 声明,我希望能够做到:

Mapper.Map(brothers, dest);

我不知道如何让它工作。 我可以像这样设置配置:

CreateMap<IEnumerable<SourceSiblings>, DestinationOuter>();

但这无济于事。 看来我需要能够说类似的话:

CreateMap<IEnumerable<SourceSiblings>, DestinationOuter>()
       .ForMember(dest => dest.Siblings,
                  opt => opt.MapFrom(src => src));

虽然上述编译, Mapper.Map实际上并没有 map 值。

这段代码似乎对我有用,但你所说的几乎没有任何作用。

internal class Program
{
    private static void Main(string[] args)
    {
        SourceSiblings[] brothers = {
                                        new SourceSiblings {Name = "A", Relation = 1},
                                        new SourceSiblings {Name = "B", Relation = 2}
                                    };
        var dest = new DestinationOuter();

        Mapper.CreateMap<SourceSiblings, DestinationInner>();

        Mapper.CreateMap<IEnumerable<SourceSiblings>, DestinationOuter>()
            .ForMember(d => d.Name, opt => opt.Ignore())
            .ForMember(d => d.Age, opt => opt.Ignore())
            .ForMember(d => d.Siblings, opt => opt.MapFrom(s => s));

        Mapper.Map(brothers, dest);
        Console.Write(dest.Siblings.Count);
        Console.ReadLine();
    }
}

public class DestinationOuter
{
    public string Name { get; set; }
    public int Age { get; set; }
    public List<DestinationInner> Siblings { get; set; }
}

public class DestinationInner
{
    public string Name { get; set; }
    public int Relation { get; set; }
}

public class SourceSiblings
{
    public string Name { get; set; }
    public int Relation { get; set; }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM