如何在AutoMapper中合并两个对象?

时间:2014-10-21 16:08:39

标签: c# automapper automapper-2

鉴于以下内容:

public class NameValueContainer
{
    public string Name { get; set; }
    public IList<string> Values { get; set; }
}

var first = new NameValueContainer
{
    Name = "First",
    Values = new List<string> { "Value1", "Value2" }
}

var second = new NameValueContainer
{
    Name = "Second",
    Values = new List<string> { "Value3" }
}

使用AutoMapper,如何合并firstsecond,以便我留下?:

姓名:“第一”

值:“Value1”,“Value2”,“Value3”

2 个答案:

答案 0 :(得分:1)

正如评论所指出的那样,将其与AutoMapper联系起来并不是很有意义。最简单的方法是使用Linq:

var merged = new NameValueContainer
{
    Name = first.Name,
    Values = first.Values.Union(second.Values).ToList()
};
//merged.Values: "Value1", "Value2", "Value3"

答案 1 :(得分:1)

嗯,我知道它没有多大意义,但在这样的自动播放器中它是可能的。

public class NameValueMerger : ITypeConverter<IList<string>, IList<string>>
{
    public IList<string> Convert(ResolutionContext context)
    {
        var source = context.SourceValue as IList<string>;
        var destination = context.DestinationValue as IList<string>;
        if (source != null &&
            destination != null)
        {
            return destination.Concat(source).ToList();
        }
        throw new ArgumentException("Types not compatible for converter.");
    }
}

public class NameValueContainer
{
    public string Name { get; set; }
    public IList<string> Values { get; set; }
}

internal class Program
{
    static Program()
    {
        Mapper.CreateMap<NameValueContainer, NameValueContainer>();
        Mapper.CreateMap<IList<string>, IList<string>>().ConvertUsing(new NameValueMerger());            
    }

    private static void Main(string[] args)
    {
        var first = new NameValueContainer { Name = "First", Values = new List<string> { "Value1", "Value2" } };
        var second = new NameValueContainer { Name = "Second", Values = new List<string> { "Value3" } };

        var result = Mapper.Map(second, first);

        Console.Write("Value : " + string.Join(", ", result.Values));
        Console.WriteLine();
    }
}

这个输出将是

Value : Value1, Value2, Value3
Press any key to continue . . .

只是说 - 因为你可能并不意味着你应该:)