使用相同枚举类型的属性将枚举映射到类

时间:2011-08-16 22:39:25

标签: c# automapper

假设我有一个具有以下定义的类:

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);

但我希望能够做的是直接从SourceSiblings映射到DestinationOuter。在这种情况下,映射中将忽略DestinationOuter中的名称和年龄属性,但我们的想法是SourceSiblings将映射到DestinationOuter.Siblings。使用上面的对象声明,我希望能够:

Mapper.Map(brothers, dest);

我不确定如何让它发挥作用。我可以这样设置配置:

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

但这没有任何作用。看起来我需要能说出类似的话:

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

虽然上面的编译,Mapper.Map实际上并没有映射值。

1 个答案:

答案 0 :(得分:1)

这段代码似乎对我有用,但它几乎就是你所说的没有做任何事情。

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; }
}