【发布时间】:2020-01-10 13:59:23
【问题描述】:
我已经定义了从一种类型到 DTO 的映射。另一种类型将第一种类型作为属性引用,但输出应该是一个扁平的 DTO,它应该使用第一种类型的已定义映射。
class Program {
static void Main(string[] args) {
var mapperConfiguration = new MapperConfiguration(cfg => {
cfg.CreateMap<FirstDataType,
FirstTypeDto>().ForMember(d => d.TypeResult, opt => opt.MapFrom(s => s.ToString()));
/* HOW TO CONFIGURE MAPPING OF THE 'FirstData' PROPERTY TO USE THE ABOVE DEFINED MAPPING
cfg.CreateMap<SecondDataType, SecondTypeDto>()
*/
});
var firstData = new FirstDataType {
TypeName = "TestType",
TypeValue = "TestValue"
};
var secondData = new SecondDataType {
Id = 1,
Name = "Second type",
FirstData = firstData
};
var mapper = mapperConfiguration.CreateMapper();
var firstDto = mapper.Map<FirstTypeDto>(firstData);
var secondDto = mapper.Map<SecondTypeDto>(secondData);
Console.ReadKey(true);
}
}
public class FirstDataType {
public string TypeName {
get;
set;
}
public string TypeValue {
get;
set;
}
public override string ToString() {
return $ "{TypeName}: {TypeValue}";
}
}
public class SecondDataType {
public int Id {
get;
set;
}
public string Name {
get;
set;
}
public FirstDataType FirstData {
get;
set;
}
}
public class FirstTypeDto {
public string TypeName {
get;
set;
}
public string TypeValue {
get;
set;
}
public string TypeResult {
get;
set;
}
}
public class SecondTypeDto: FirstTypeDto {
public int Id {
get;
set;
}
public string Name {
get;
set;
}
}
我应该如何配置第二种类型的映射以使用属性“FirstData”的定义映射?
谢谢!
【问题讨论】:
-
SecondDataType是否应该像其对应的 DTO 一样从FirstDataType继承? -
请添加预期结果。
-
是的,它应该扩展
FirstDataType,将其映射为展平,但使用已经定义的映射(以保持代码干燥)。 -
我认为:
cfg.CreateMap<SecondDataType, SecondTypeDto>() .ForMember(d => d.TypeName, opt => opt.MapFrom(s => s.FirstData.TypeName )) .ForMember(d => d.TypeValue, opt => opt.MapFrom(s => s.FirstData.TypeValue )) .ForMember(d => d.TypeResult, opt => opt.MapFrom(s => s.FirstData.ToString() )); -
在我看来你只需要使用
IncludeMembers和Include。
标签: c# .net-core automapper automapper-6