自动映射 - 有条件地添加到列表

时间:2015-11-30 10:51:03

标签: c# automapper

情况是 -

public class One
{
    public string S1 { get;set; }
    public string S2 { get;set; }
    public string S3 { get;set; }
    public string S4 { get;set; }
}

public class Two
{
    public List<string> List1 { get;set; }
}

现在我想要的是使用Two的非null属性值填充One内的列表。

使用AutoMapper

来实现此目的还是可以吗?

2 个答案:

答案 0 :(得分:2)

在这种情况下,您可以创建自己的自定义值解析器:

public class CustomResolver : ValueResolver<One, List<string>>
{
    protected override List<string> ResolveCore(One source)
    {
        var result = new List<string>();

        //your logic
        if (!string.IsNullOrWhiteSpace(source.S1))
            result.Add(source.S1);

        if (!string.IsNullOrWhiteSpace(source.S2))
            result.Add(source.S2);

        if (!string.IsNullOrWhiteSpace(source.S3))
            result.Add(source.S3);

        if (!string.IsNullOrWhiteSpace(source.S4))
            result.Add(source.S4);

        return result;
    }
}

映射配置:

Mapper.CreateMap<One, Two>()
    .ForMember(dest => dest.List1, opt => opt.ResolveUsing<CustomResolver>());

通过这种方式,您可以为特定属性配置映射

答案 1 :(得分:2)

如果这是您希望在类之间进行的唯一映射,则可以使用自定义类型转换器:这将完全控制对象之间的映射。

public class OneTwoTypeResolver : TypeConverter<One, Two>
{
    protected override Two ConvertCore(One source)
    {
        Two two = new Two {List1 = new List<string>()};

        if (source.S1 != null)
            two.List1.Add(source.S1);

        if (source.S2 != null)
            two.List1.Add(source.S2);

        if (source.S3 != null)
            two.List1.Add(source.S3);

        if (source.S4 != null)
            two.List1.Add(source.S4);

        return two;
    }
}

您告诉AutoMapper在类之间进行映射时使用此类:

Mapper.CreateMap<One, Two>().ConvertUsing<OneTwoTypeResolver>();

然后这个测试将通过:

public void Test()
{
    One one = new One {S2 = "OneTwoThreeFour"};
    Two two = Mapper.Map<One, Two>(one);
    Assert.AreEqual(1, two.List1.Count);
    Assert.AreEqual("OneTwoThreeFour", two.List1.Single());
}
相关问题