如何在 C# 中使用 Automapper 将数组映射到数组

How to map array to array using Automapper in C#

我有以下源和目标 class。

public class Source
    {
        public string BookName { get; set; }
        public Bookstore[] BookStore { get; set; }
    }

    public class Bookstore
    {
        public Address[] Address { get; set; }
    }

    public class Address
    {
        public string Street { get; set; }
    }

目标class如下

public class Target

    {
        public string Book { get; set; }
        public Store[] Store { get; set; }
    }
    public class Store
    {
        public Geo Geo { get; set; }
    }

    public class Geo
    {
        public Location[] Location { get; set; }
    }

    public class Location
    {
        public string Street { get; set; }
    }

我正在寻找正确映射的解决方案,将源文件数据复制到目标字段,如下所示,

CreateMap<Source, Target>()
                .ForMember(dest => dest.Book, o => o.MapFrom(src => src.BookName));
               
CreateMap<Bookstore, Store>()
                .ForMember(dest => dest.Geo.Location, o => o.MapFrom(src => src.Address));

但我看到一些错误,例如“解析为顶级成员”等或数组字段、地理和位置仍然为空。

我想将源数据映射到目标。

下面是源文件示例

var jsonText = @"                      
{
  "BookName": "Test",
  "BookStore": [
    {
      "Address": [
        {
          "Street": "1234"
        }
      ]
    }
  ]
}";


            var sourType = JsonConvert.DeserializeObject<Source>(jsonText);

预期的目标文件如下,其中添加了“Geo”对象,

{
  "Book": "Test",
  "Store": [
    {
      "Geo": {
        "Location": [
          {
            "Street": "1234"
          }
        ]
      }
    }
  ]
}

您需要为这种类型的包装定制一个转换器。虽然根据您的模型,您的 JSON 结果应该是这样的:

{
  "Book": "Test",
  "Store": [
    {
      "Geo": {
        "Location": [
          {
            "Street": "1234"
          }
        ]
      }
    }
  ]
}

顺便说一句,这里是解决方案:

Expression < Func < Bookstore, Store >> storeConverter = p => (new Store {
  Geo = new() {
    Location = p.Address
      .Select(ad => new Location {
        Street = ad.Street
      }).ToArray()
  }
});

CreateMap < Source, Target > ()
  .ForMember(dest => dest.Book, o => o.MapFrom(src => src.BookName))
  .ForMember(dest => dest.Store, o => o.MapFrom(src => src.BookStore));

CreateMap < Bookstore, Store > ()
  .ConvertUsing(storeConverter);

您可以将表达式移动到单独的 class 类型的转换器中以获得更简洁的代码。请参阅文档中的详细信息 https://docs.automapper.org/en/stable/Custom-type-converters.html