在我的项目中,我有:
StartUp.cs
var carDtos = JsonConvert.DeserializeObject<IEnumerable<CarDto>>(inputJson);
var cars = mapper.Map<IEnumerable<Car>>(carDtos);
在这里,我使用 DTO 模型反序列化 JSON 文件,然后尝试将这些模型映射到 Car 类。我收到错误 - 映射类型错误。
汽车.cs
public class Car
{
public int Id { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public long TravelledDistance { get; set; }
public ICollection<Sale> Sales { get; set; }
public ICollection<PartCar> PartCars { get; set; } = new List<PartCar>();
}
CarDto.cs
public class CarDto
{
public string Make { get; set; }
public string Model { get; set; }
public long TravelledDistance { get; set; }
public ICollection<int> PartsId { get; set; }
}
汽车.json
[
{
"make": "Opel",
"model": "Astra",
"travelledDistance": 516628215,
"partsId": [
39,
62,
72
]
},
{
"make": "Opel",
"model": "Astra",
"travelledDistance": 156191509,
"partsId": [
48,
44,
112
]
}
]
CarDealerProfile.cs
public class CarDealerProfile : Profile
{
public CarDealerProfile()
{
this.CreateMap<Car, CarDto>()
.ForMember(dest =>
dest.PartsId,
opt => opt.MapFrom(src => src.PartCars));
}
}
我知道代码不起作用,因为我没有正确映射,但我就是无法弄清楚。
我想通过位于 Car 类中的映射表 PartCars 映射名为 partsId 的 JSON 数组中的数字并保存这些数字作为 Part 类的 Id。
最佳答案
在您的 Profile
中您从 Car
定义了映射至CarDto
但在您的代码中,您试图从 CarDto
进行映射至Car
。为了能够绘制两个方向的 map ,请添加 ReverseMap()
。您还需要告诉automapper如何转换int
至PartCar
和PartCar
至int
这样它就可以映射ICollection<PartCar> PartCars
属性至ICollection<int> PartsId
属性(property),反之亦然。试试这个:
public class CarDealerProfile : Profile
{
public CarDealerProfile()
{
CreateMap<Car, CarDto>()
.ForMember(dest => dest.PartsId, opt => opt.MapFrom(src => src.PartCars))
.ReverseMap();
CreateMap<PartCar, int>().ConvertUsing(o => o.PartId);
CreateMap<int, PartCar>().ConvertUsing(o => new PartCar { PartId = o });
}
}
关于c# - 如何使用 AutoMapper 将数字数组映射到映射表内的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73764797/