automapper - AutoMapper 不同级别
问题描述
尝试从 Customer 映射到 CustomerDto 但在源中的那个额外层有问题(我无法控制源,所以很遗憾我无法对齐两者)。
public class Customer
{
public string Name { get; set; }
public AddressSet AddressSet { get; set; }
}
public class AddressSet
{
public AddressSetResults[] AddressSetResults { get; set; }
}
public class AddressSetResults
{
public string Street { get; set; }
public string HouseNumber { get; set; }
}
public class CustomerDto
{
public string Name { get; set; }
public AddressDto AddressDto { get; set; }
}
public class AddressDto
{
public string Street { get; set; }
public string HouseNumber { get; set; }
}
以下不适用于AddressDto,知道我缺少什么吗?
CreateMap<Customer, CustomerDto>()
.ForMember(dest => dest.AddressDto , opt => opt.MapFrom(src => src.AddressSet.AddressSetResults))
解决方案
两件事情:
1) 缺少从 AddressSetResults 到 AddressDto 的映射
为了映射内部地址,您还需要为这些内部类型创建映射:
CreateMap<AddressSetResults, AddressDto>();
2) 从 AddressSetResults 数组的元素映射,而不是从数组本身映射
这种方法:
.ForMember(
dest => dest.AddressDto,
opt => opt.MapFrom(src => src.AddressSet.AddressSetResults))
告诉 AutoMapper 映射到AddressDto
哪个AddressSetResults
是AddressSetResults
. 这是不正确的,因为 AutoMapper 不知道如何从元素数组映射到一个元素。除非您也为此创建地图,否则这不是一个好的解决方案。
假设AddressSetResults
最多包含一个地址,您可以解决FirstOrDefault()
在映射表达式末尾再添加一个调用的问题:
.ForMember(
dest => dest.AddressDto,
opt => opt.MapFrom(src => src.AddressSet.AddressSetResults.FirstOrDefault()))
FirstOrDefault()
需要System.Linq
命名空间。
为什么不只是First()
?如果源AddressSetResults
数组不包含任何元素,则映射将失败并导致异常,因为找不到满足First()
方法调用的元素。使其抵抗无元素场景FirstOrDefault()
是更安全的解决方案。
最终的工作配置:
CreateMap<Customer, CustomerDto>()
.ForMember(
dest => dest.AddressDto,
opt => opt.MapFrom(src => src.AddressSet.AddressSetResults.FirstOrDefault()));
CreateMap<AddressSetResults, AddressDto>();
推荐阅读
- laravel - 是否可以以 Octobercms 形式有多个数据请求?
- java - 如何从spring data jpa中的子主键获取父实体?
- c# - 在实体框架中使用 TPT 设计的多级继承
- azure-iot-hub - 如何在 Linux 和 C# 上为 Azure DPS 使用 TPM 上生成的 X.509 证书
- excel - 查找某个值的列中的所有重复项,并从下一列返回值
- contentful - 编辑器将内容推送到 Contentful
- jquery - 如何使模式弹出窗口中的“X”按钮重定向到另一个站点
- sql - 具有唯一列值的 pyspark 数据帧数据转换
- nativescript - 在 nativescript-angular 项目中创建形状
- c++ - C++:移至 unique_ptr