如何在AutoMapper中合并两个对象

本文关键字:两个 对象 合并 AutoMapper | 更新日期: 2023-09-27 18:27:17

给定以下条件:

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"

如何在AutoMapper中合并两个对象

正如评论所指出的,将其与AutoMapper绑定并没有真正的意义。最简单的方法是使用Linq:

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

嗯,我知道这没有多大意义,但在这样的自动映射程序中是可能的。

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 . . .

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