代码改变世界

AutoMapper在.NetCore中实现两个对象的映射(复制)

2020-08-01 14:16  石吴玉  阅读(1019)  评论(0编辑  收藏  举报

添加NuGet包:AutoMapper

类1:

public class AuditLog
  {
    public string SystemTag { get; set; }

    public string BeforeContent { get; set; }

    public string AfterContent { get; set; }

    public DateTime OperateDateTime { get; set; }
    }
}

类2:

public class QueryAuditLogDto
{
    public string SystemTag { get; set; }

    public string BeforeContent { get; set; }

    public string AfterContent { get; set; }

    public string [] OperateDateTime { get; set; }
}

把类1复制给类2,并改变其中字段的类型或表现形式

          List<Models.AuditLog> listAuditLog = db.Query<Models.AuditLog>( SourceSql).ToList();
          List<QueryAuditLogDto> listAuditLogDto = new List<QueryAuditLogDto>();
          var config = new MapperConfiguration( cfg => cfg.CreateMap<Models.AuditLog, QueryAuditLogDto>()
            .ForMember(d=>d.BeforeContent ,opt=>opt.MapFrom(src=>src.BeforeContent.Replace( "{\"", "" ).Replace( "\"}", "" ).Replace( "\":\"", "=" ).Replace( "\",\"", "," ) ) )
            .ForMember(d=>d.AfterContent,opt=>opt.MapFrom(src=>src.AfterContent.Replace( "{\"", "" ).Replace( "\"}", "" ).Replace( "\":\"", "=" ).Replace( "\",\"", "," ) ) )
            .ForMember(d=>d.OperateDateTime,opt=>opt.MapFrom(src=> new string[] { src.OperateDateTime.ToString( "yyyy-MM-dd HH:mm:ss" ) } ))
          );
          var mapper = config.CreateMapper();
          listAuditLogDto = mapper.Map<List<QueryAuditLogDto>>( listAuditLog );