AutoMapper文档:http://docs.automapper.org/en/stable/The-MyGet-build.html
新的版本抛弃了静态API方法,我们将使用依赖注入来完成。
①添加包
②创建MyAutoMapper.cs文件来创建实体和Dto之间的映射关系
public class MyAutoMapper : Profile { public MyAutoMapper() { //实体和Dto的相互转化 CreateMap<PFUserDto, PFUser>().ReverseMap(); } }
/// <summary> /// 用户表 /// </summary> [Table("PF_User")] public class PFUser { /// <summary> /// 主键 /// </summary> [Column("UserGuid")] [Display(Name = "用户表主键", Description = "用户表主键")] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public Guid Id { get; set; } /// <summary> /// 用户名 /// </summary> [Display(Description = "用户名", Name = "用户名")] [Column("UserName")] [StringLength(128)] public string UserName { get; set; } /// <summary> /// 密码 /// </summary> [Display(Description = "密码", Name = "密码")] [Column("UserPassWord")] [StringLength(256)] public string UserPassWord { get; set; } /// <summary> /// 是否删除 /// </summary> [Display(Description = "是否删除", Name = "是否删除")] [Column("IsDeleted")] public byte? IsDeleted { get; set; } /// <summary> /// 创建日期 /// </summary> [Display(Description = "创建日期", Name = "创建日期")] [Column("CreateDate")] public DateTime? CreateDate { get; set; } }
public class PFUserDto { /// <summary> /// 主键 /// </summary> [Column("UserGuid")] [Display(Name = "用户表主键", Description = "用户表主键")] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public Guid Id { get; set; } /// <summary> /// 用户名 /// </summary> [Display(Description = "用户名", Name = "用户名")] [Column("UserName")] [StringLength(128)] public string UserName { get; set; } /// <summary> /// 密码 /// </summary> [Display(Description = "密码", Name = "密码")] [Column("UserPassWord")] [StringLength(256)] public string UserPassWord { get; set; } /// <summary> /// 是否删除 /// </summary> [Display(Description = "是否删除", Name = "是否删除")] [Column("IsDelte")] public byte? IsDeleted { get; set; } /// <summary> /// 创建日期 /// </summary> [Display(Description = "创建日期", Name = "创建日期")] [Column("CreateDate")] public DateTime? CreateDate { get; set; } public string MyProperty { get; set; } }
③添加服务
④使用:实体转Dto,Dto转实体也是一样的
ProjectTo<>方法:
值的转化,我们想给前端传的时间是字符串形式的,AutoMapper还允许我们自定义转化器来转化我们的数据类型
①创建DateTimeTypeConverter.cs文件
/// <summary> /// DateTime2string /// </summary> public class DateTimeTypeConverter : ITypeConverter<DateTime, string> { public string Convert(DateTime source, string destination, ResolutionContext context) { return source.ToString("yyyy-MM-dd HH:mm:ss"); } }
添加类型映射关系
public class MyAutoMapper : Profile { public MyAutoMapper() { // 可以给lambda表达式 //CreateMap<DateTime, string>().ConvertUsing(x => x.ToString("yyyy-MM-dd HH:mm:ss")); //实现接口 CreateMap<DateTime, string>().ConvertUsing<DateTimeTypeConverter>(); //实体和Dto的相互转化 CreateMap<PFUserDto, PFUser>().ReverseMap(); } }
修改我们的Dto CreateDate类型
使用:字符串转时间
时间转字符串
还有别的就自己看文档吧