AutoMapper框架

官方文档

什么是AutoMapper 

AutoMapper 是一个对象-对象映射器。对象-对象映射通过将一种类型的输入对象转换为不同类型的输出对象来工作。

AutoMapper的优点

现在的软件开发都是分层结构的,一个对象或实体有自己所使用的范围,在层与层之间就存在着大量的对象和实体的转换,AutoMapper可以通过对象和对象之间的映射关系的配置很好的解决对象在边界的转化问题

AutoMapper的使用(net core 3.1)

1、通过nuge添加项目引用

AutoMapper

2、实体类

public class Source
{
    public string Value { get; set; }
}
public class Destination
{
    public string Value { get; set; }
}

3、实例化MapperConfiguration并添加映射配置

MapperConfiguration config = new MapperConfiguration(cfg =>
    {
        //左边为源右边为转换实体
        cfg.CreateMap<Source, Destination>();
        cfg.CreateMap<Destination, Source>();
    }
);

4、通过MapperConfiguration对象创建IMapper(映射处理器)

IMapper mapper = config.CreateMapper();

5、通过IMapper进行对象映射

复制代码
Source source = new Source()
{
    Value = "SourceValue"
};
Destination destination = new Destination()
{
    Value = "DestinationValue"
};
Destination o1 = mapper.Map<Destination>(source);
Source o2 = mapper.Map<Source>(destination);
复制代码

其他实例化MapperConfiguration时配置加载方式

1、通过AddProfile加载配置类

继承profile配置的最终还是调用IProfileExpression接口中的CreateMap方法,方式不同

public class CustomProfile : Profile
{
    public CustomProfile()
    {
        CreateMap<DataEntity, DataDto>();
        CreateMap<DataDto, DataEntity>();
    }
}

 

MapperConfiguration config = new MapperConfiguration(cfg =>
{
    cfg.AddProfile<CustomProfile>();
});

2、在程序集中搜索Profile的继承

MapperConfiguration config = new MapperConfiguration(cfg =>
{
    //从程序集中搜索
    cfg.AddMaps(Assembly.GetExecutingAssembly());
});

映射规则配置

默认不配置映射规则只能转换相同名称相同类型的属性,AutoMapper提供了多种映射规则的配置来进行对象之间的转换

1、实体类

public class DataDto
{
    public string Id { get; set; }
    public string Property1 { get; set; }
    public string Property2 { get; set; }
}

 

public class DataEntity
{
    public string Guid { get; set; }
    public int? Property1 { get; set; }
    public double Property2 { get; set; }
}

2、指定属性名称的映射

MapperConfiguration config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<DataDto, DataEntity>()
        //配置映射,指定目标和源的映射关系
        .ForMember(dest => dest.Guid, opt => opt.MapFrom(src => src.Id));
});

3、自定义解析器

复制代码
public class CustomResolver : IValueResolver<DataDto, DataEntity, string>
{
    public string Resolve(DataDto source, DataEntity destination, string destMember, ResolutionContext context)
    {
        return source.Id;
    }
}

MapperConfiguration config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<DataDto, DataEntity>()
        //自定义解析器
        .ForMember(dest => dest.Guid, opt => opt.MapFrom<CustomResolver>());
});
复制代码

4、对null的处理

MapperConfiguration config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<DataDto, DataEntity>()
        //对null的处理
        .ForMember(dest => dest.Property1, opt => opt.NullSubstitute("0"));
});

5、条件映射,映射约束

MapperConfiguration config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<DataDto, DataEntity>()
        //条件映射,映射约束
        .ForMember(dest => dest.Property1, opt => opt.Condition(src => src.Property1 != null));
});

6、自定义映射

复制代码
MapperConfiguration config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<DataDto, DataEntity>()
        //自定义映射
        .ConvertUsing((s, j) =>
        {
            DataEntity result = new DataEntity();
            result.Guid = s.Id;
            result.Property1 = 0;
            result.Property2 = 0.0f;

            return result;
        });
});
复制代码

7、泛型的映射

实体类

public class Source<T>
{
    public T Value { get; set; }
}
public class Destination<T>
{
    public T Value { get; set; }
}

配置

MapperConfiguration config = new MapperConfiguration(cfg => cfg.CreateMap(typeof(Source<>), typeof(Destination<>)));
IMapper mapper = config.CreateMapper();
var source = new Source<int> { Value = 10 };
var dest = mapper.Map<Source<int>, Destination<int>>(source);

和依赖注入框架的配合使用

1、通过nuge添加项目引用

Microsoft.Extensions.DependencyInjection

AutoMapper.Extensions.Microsoft.DependencyInjection

2、实体类

class DIAutoMapperObj
{
    private readonly IMapper _mapper;
    public DIAutoMapperObj(IMapper mapper)
    {
        _mapper = mapper;
    }
}

3、通过服务注册的方式注册和配置AutoMapper

这样可以由DI来进行管理对象的创建工作

var provider = new ServiceCollection()
    //以服务注册的方式进行配置
    .AddAutoMapper(cfg => cfg.CreateMap(typeof(Source<>), typeof(Destination<>)))
    .AddSingleton<DIAutoMapperObj>();
DIAutoMapperObj dIAutoMapperObj = provider.BuildServiceProvider().GetService<DIAutoMapperObj>();

 

posted @   .NET_CJL  阅读(127)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示