最近在项目中要用到mapping,因为在业务逻辑层返回数据给UI层的时候,最好把数据转换成UI层所需要的Dto对象。
之前都是使用automap,最近听说使用Mapster速度比automap更快,所以想尝试尝试。
但是网上关于Mapster的介绍比较少,基本都是很简单的使用,很少有关于属性对象映射的介绍。
比如汽车是一个对象,汽车包含有4个轮子,而轮子有是一个对象,甚至轮子可能还包含其它对象。
从数据库里查询出来的汽车对象是包含有轮子子对象的,所以映射的时候是要把汽车对象及其属性对象(轮子)一起映射出来。
后来找到了一篇接近的文章介绍,是关于自引用对象映射的,也就是父节点包含子节点,
子节点又有可能包含子节点,而父节点与子节点是属于同一个类型的,不过也有参考价值,
连接:https://stackoverflow.com/questions/62324239/how-to-map-self-reference-with-mapster
好了,废话少说,直接动手。
先分别创建3个类,ClassSampleA、ClassSampleB、ClassSampleC:
public class ClassSampleA
{
public int ID { get; set; }
public string Name { get; set; }
public List<ClassSampleB> ClassSampleBList { get; set; } = new List<ClassSampleB>();
}
public class ClassSampleB
{
public int ID { get; set; }
public string Name { get; set; }
public List<ClassSampleC> ClassSampleCList { get; set; } = new List<ClassSampleC>();
}
public class ClassSampleC
{
public int ID { get; set; }
public string Name { get; set; }
}
然后再创建与之对应的Dto:
public class ClassSampleADto
{
public int ID { get; set; }
public string Name { get; set; }
public List<ClassSampleBDto> ClassSampleBDtoList { get; set; } = new List<ClassSampleBDto>();
}
public class ClassSampleBDto
{
public int ID { get; set; }
public string Name { get; set; }
public List<ClassSampleCDto> ClassSampleCDtoList { get; set; } = new List<ClassSampleCDto>();
}
public class ClassSampleCDto
{
public int ID { get; set; }
public string Name { get; set; }
}
然后创建映射规则配置:
public class MappingConfig
{
public static TypeAdapterConfig GetClassSampleADtoWithBAndC()
{
TypeAdapterConfig config = new TypeAdapterConfig();
config.ForType<ClassSampleA, ClassSampleADto>().Map(dto => dto.ClassSampleBDtoList, d => d.ClassSampleBList.Adapt<List<ClassSampleBDto>>(GetListClassSampleBDto()));
return config;
}
public static TypeAdapterConfig GetListClassSampleBDto()
{
TypeAdapterConfig config = new TypeAdapterConfig();
config.ForType<ClassSampleB, ClassSampleBDto>().Map(dto => dto.ClassSampleCDtoList, d => d.ClassSampleCList.Adapt<List<ClassSampleCDto>>());
return config;
}
}
调用代码如下:
var classSampleADto = classSampleA.Adapt<ClassSampleADto>(MappingConfig.GetClassSampleADtoWithBAndC());
大功告成。
代码:链接:https://pan.baidu.com/s/1fzFmtRt9ltJLDJQ9rJypCg
提取码:1234
复制这段内容后打开百度网盘手机App,操作更方便哦