RobotMapper是码云上一款开源工具,地址:https://gitee.com/wuyuege/RobotMapper
一、RobotMapper诞生背景
- 在日常项目开发中,需要将数据访问层的Entity转化为数据传输层的DTO,或者将数据传输层的DTO转化为前端的ViewModel,而手写转换方法很烦,而且随着结构的增加,类的增加,代码量会比较大且不利于更新维护,因此需要一款能够自动映射工具帮我们实现这些工作。
- 我们对映射工具也有如下要求:
- 转化效率必须高:显然,查询数据只需要0.001毫秒但是映射花费1秒这是我们不能接受的;
- 配置必须简单甚至无需配置或者自动配置:每次映射都需要进行复杂的配置无异于手动映射让人烦躁;
- 解决循环引用问题:尤其是数据访问层,由于数据库表之间的关系,我们的Entity会有很多一对一,一对多,多对多的导航属性,类型之间的互相引用必不可少,传统的映射工具无法自动解决该问题,要么进入死循环要么映射效率低下;
二、使用
public class User
{
public string Id { get; set; }
public string Name { get; set; }
public string Code { get; set; }
public string Department { get; set; }
}
public class DtoUser
{
public string Id { get; set; }
public string Name { get; set; }
public string Code { get; set; }
public string Department { get; set; }
}
1、 简单映射和批量映射
//简单映射
User user = new User();
DtoUser dtouser = user.RobotMap<User, DtoUser>();
//批量映射
List<User> lstUser = new List<User>();
List<DtoUser> lstDtoUser = lstUser.RobotMap<User, DtoUser>();
2、支持自定义映射配置、支持忽略属性
支持自定义映射配置
DtoUser dtouser = user.RobotMap<User, DtoUser>(config=>
{
config.Bind(x => x.Id, y => Id);
config.BindName(x => x.Name, y => y.Name);
});
支持忽略属性
DtoUser dtouser = user.RobotMap<User, DtoUser>(config=>
{
config.Ignore(y => y.Code);
config.Ignore("Department", "Name");
});