3AutoMapper In Asp.net Core

知是行的主意,行是知的功夫。这篇文章主要讲述3AutoMapper In Asp.net Core相关的知识,希望能为你提供帮助。

目录

  • Entity & & ViewModel
    • 实体类代码
    • Dto (ViewModel)
    • CompaniesController
  • AutoMapper
    • 1. 添加nuget
    • 2. 注册服务
    • 3. 建立映射类
    • 4. 在Controller中使用AutoMaper
      • 4.2 使用AutoMapper代替Foreach遍历

Entity & & ViewModel
  • Entities-- 实体模型
    • Company.cs-- 公司实体类
    • Employee.cs -- 公司职员实体类
      • Gender -- 性别枚举类型
  • Models-- Dto(ViewModel)
    • CompanyDto
实体类代码Company
public class Company { public Guid Id { get; set; } public string Name { get; set; } public string Country { get; set; } public string Industry { get; set; } public string Product { get; set; } public string Introduction { get; set; }public DateTime? BankruptTime { get; set; }public ICollection< Employee> Employees { get; set; } }

Employee + Gender
public class Employee { public Guid Id { get; set; } public Guid CompanyId { get; set; }public string EmployeeNo { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public Gender Gender { get; set; } public DateTime DateOfBirth { get; set; }public Company Company { get; set; } }public enum Gender { 男 = 1, 女 = 2 }

Dto (ViewModel)CompanyDto
public class CompanyDto { public Guid Id { get; set; } public string CompanyName { get; set; } }

CompaniesController原始的获取方法
public async Task< IActionResult> GetCompanies() { var companies = await .companyRepository.GetCompaniesAsync(); var companyDtos = new List< CompanyDto> (); foreach (var company in companies) { companyDtos.Add(new CompanyDto Id = company.Id, Name = company.Name }); } return ok(companyDtos); }

AutoMapper 1. 添加nuget
3AutoMapper In Asp.net Core

文章图片

2. 注册服务
扫描当前应用域下面的程序集
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

3. 建立映射类【3AutoMapper In Asp.net Core】新建CompanyProfile.csProfile类
public class CompanyProfile : Profile { public CompanyProfile() { CreateMap< Company, CompanyDto> ()// 映射 .ForMember(// 按照默认规则无法映射成功的 dest => dest.CompanyName,// 目标属性 CompanyDto.CompanyName opt => opt.MapFrom(src =https://www.songbingjia.com/android/> src.Name)); //指定目标从哪里来Company CreateMap< CompanyAddDto, Company> (); CreateMap< Company, CompanyFullDto> (); CreateMap< CompanyAddWithBankruptTimeDto, Company> (); } }

4. 在Controller中使用AutoMaper
### 4.1 注入

private readonly IMapper _mapper;

public CompaniesController(IMapper mapper) { _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper)); // 检查mapper 是否为null }

4.2 使用AutoMapper代替Foreach遍历
public async Task< ActionResult< IEnumerable< CompanyDto> > > GetCompanies( ) { var companies = await_ companyRepos itory .GetCompaniesAsync(); var companyDtos = _mapper.Map< IEnumerable< CompanyDto> > (companies)return 0k( companyDtos); }


    推荐阅读