如何将对象映射到列表<Object> c# Automapper

How to map Object to List<Object> c# Automapper

关于如何将单个对象映射到列表的任何想法? 我有:

class AdditionalData:
string data1
string data2
string data3

class Person:
AdditionalData additionalData
string UCN

class AdditionalDataDTO:
string data1
string data2
string data3
string data4
string data5

class PersonDTO:
AdditionalDataDTO additionalData[]
string UCN

那么如何将AdditionalData映射到List 我希望源成为列表中的第一个对象 我知道如何将 AdditionalData 映射到 AdditionalDataDTO

如果您能提供一个完整的代码示例,其中包含您当前的状态和失败的地方,那就容易多了。所以我不得不自己编写代码,而不是简单地从你的问题中复制它。尽管如此,我还是努力在自己身上设置了一切,也找到了解决方案。 ;-)

与 AutoMapper 一样,缺少的点是 .ConvertUsing() 的用法和提供 ResolutionContext 的重载,它允许访问映射器本身以进行递归调用:

using AutoMapper;

namespace ConsoleApp
{
    public static class Program
    {
        static void Main(string[] args)
        {
            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<Person, PersonDTO>();
                cfg.CreateMap<AdditionalData, AdditionalDataDTO>();
                cfg.CreateMap<AdditionalData, AdditionalDataDTO[]>()
                    .ConvertUsing((s, _, context) =>
                    {
                        var single = context.Mapper.Map<AdditionalDataDTO>(s);
                        return new[] { single };
                    });
            });

            var mapper = config.CreateMapper();

            var source = new Person
            {
                UCN = "MyName",
                AdditionalData = new AdditionalData
                {
                    Data1 = "First",
                    Data2 = "Second",
                    Data3 = "Third",
                }
            };

            var dest = mapper.Map<PersonDTO>(source);
        }
    }

    public class AdditionalData
    {
        public string Data1 { get; set; }
        public string Data2 { get; set; }
        public string Data3 { get; set; }
    }

    public class Person
    {
        public string UCN { get; set; }
        public AdditionalData AdditionalData { get; set; }
    }

    public class AdditionalDataDTO
    {
        public string Data1 { get; set; }
        public string Data2 { get; set; }
        public string Data3 { get; set; }
        public string Data4 { get; set; }
        public string Data5 { get; set; }
    }

    public class PersonDTO
    {
        public string UCN { get; set; }
        public AdditionalDataDTO[] AdditionalData { get; set; }
    }
}