zoukankan      html  css  js  c++  java
  • .NET5.0 MVC AutoMapper 基本使用

    安装

    安装 NuGet 包

    install-package AutoMapper
    install-package AutoMapper.Extensions.Microsoft.DependencyInjection
    

    第一个是 AutoMapper 的包。

    第二个是扩展包,可以使用 AddAutoMapper() 方法


    使用

    前置

    这里创建两个示例,以用于相互映射。

    public class User
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }
    public class UserDto
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }
    

    配置

    创建一个 MapperProfile 类,继承 AutoMapper.Profile ,接着在其构造函数中创建映射。

    //创建一个 自定义Profile 类,继承 AutoMapper.Profile
    public class MapperProfile : Profile
    {
        public MapperProfile()
        {
            //配置映射(基本)
            CreateMap<User, UserDto>();
            //配置映射:这样映射的结果 dto.Name = user.ID + user.Name
            CreateMap<User, UserDto>()
                .ForMember(dest => dest.Name, opt => MapFrom(src => str.ID.ToString() + src.Name));
            //其他配置:驼峰命名与Pascal命名的兼容
            DestinationMemberNamingConvention = new PascalCaseNamingConvention();
            SourceMemberNamingConvention = new LowerUnderscoreNamingConvention();
        }
    }
    

    Startup.cs 中注册服务。

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAutoMapper(typeof(MapperProfile));
        //……其他代码
    }
    

    注意 :上述写法,实际上是找到 MapperProfile 所在程序集,然后扫描程序集所有继承 Profile 的 class(若同一个程序集多次出现,会重复配置。重复配置目前未发现对映射有影响)。


    使用

    在控制器中使用。

    public class HomeController : Controller
    {
        private readonly IMapper _mapper;
        
        public HomeController(IMapper mapper)
        {
            _mapper = mapper;
        }
        
        [HttpGet]
        public UserDto GetUser()
        {
            User user = new User(){ ID = 1, Name = "名字" };
            var dto = _mapper.Map<User,UserDto>(user);
            return dto;
        }
    }
    

    参考来源

    ASP.NET.Core中使用AutoMapper

  • 相关阅读:
    【Linux笔记】Linux目录结构
    《Effective C#》快速笔记(五)-
    《Effective C#》快速笔记(四)- 使用框架
    《Effective C#》快速笔记(三)- 使用 C# 表达设计
    《Effective C#》快速笔记(二)- .NET 资源托管
    《Effective C#》快速笔记(一)- C# 语言习惯
    Visual Studio 数据库架构比较
    C# 反射与dynamic最佳组合
    C# 调用WebApi
    基于微软开发平台构建和使用私有NuGet托管库
  • 原文地址:https://www.cnblogs.com/clis/p/14764829.html
Copyright © 2011-2022 走看看