【问题标题】:Automapp an object to list将对象自动映射到列表
【发布时间】:2022-01-13 16:47:42
【问题描述】:

我正在使用自动映射器来映射源类和目标类,如下所示

 var config = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<SourceClass, DestinationClass>()
            .ForMember(dest => dest.P1, act => act.MapFrom(src => src.S1))
            .ForMember(dest => dest.P2, act => act.MapFrom(src => src.S2))
            .ForMember(dest => dest.P3, act => act.MapFrom(src => src.S3));
        });
    
        IMapper mapper = config.CreateMapper();
        DestinationClass destObject= mapper.Map<DestinationClass>(sourceObj);

这里可以将单个对象映射到列表吗?喜欢cfg.CreateMap&lt;SourceClass, List&lt;DestinationClass&gt;&gt;()

映射后,我期望目标类列表具有源类的值。这意味着一个包含一个元素的列表。是否可以使用 .net core 将单个对象映射到列表?

【问题讨论】:

  • 那不编译。您有几个分号放错了位置。
  • @PalleDue ,更新了相关代码
  • @YongShun 我们可以不用自定义转换器来做到这一点
  • 您好,如果没有自定义转换器,您必须将单个 SourceClass 对象添加到 List&lt;SourceClass&gt; 数组。然后使用数组映射到List&lt;DestinationClass&gt;数组。

标签: c# asp.net-mvc asp.net-core asp.net-web-api automapper


【解决方案1】:

我认为,这应该可以解决问题:

public static class Program
{
    public static async Task Main()
    {
        var config = new MapperConfiguration(cfg => cfg.AddProfile<MappingProfile>());
        var mapper = config.CreateMapper();

        var src = new Source { S1 = "Hello", S2 = "World", S3 = "!" };

        // Create list from single item
        var destList = mapper.Map<List<Destination>>(src);
        // Output: [{"D1":"Hello","D2":"World","D3":"!"}]
        Console.WriteLine(JsonConvert.SerializeObject(destList));

        // Add item to existing list
        mapper.Map(src, destList);
        // Output: [{"D1":"Hello","D2":"World","D3":"!"},{"D1":"Hello","D2":"World","D3":"!"}]
        Console.WriteLine(JsonConvert.SerializeObject(destList));
    }
}

public class MappingProfile : Profile
{
    public MappingProfile()
    {
        CreateMap<Source, Destination>()
            .ForMember(d => d.D1, conf => conf.MapFrom(s => s.S1))
            .ForMember(d => d.D2, conf => conf.MapFrom(s => s.S2))
            .ForMember(d => d.D3, conf => conf.MapFrom(s => s.S3));

        CreateMap<Source, List<Destination>>()
            .ConvertUsing((src, destList, context) =>
            {
                if (destList == null)
                    destList = new List<Destination>();

                var dest = context.Mapper.Map<Destination>(src);
                destList.Add(dest);

                return destList;
            });
    }
}

public class Source
{
    public string S1 { get; set; }
    public string S2 { get; set; }
    public string S3 { get; set; }
}

public class Destination
{
    public string D1 { get; set; }
    public string D2 { get; set; }
    public string D3 { get; set; }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-28
    • 1970-01-01
    • 2020-05-12
    • 1970-01-01
    • 2021-11-07
    • 2019-12-06
    相关资源
    最近更新 更多