3AutoMapper In Asp.net Core

Posted 乾子大大

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了3AutoMapper In Asp.net Core相关的知识,希望对你有一定的参考价值。

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

2. 注册服务

扫描当前应用域下面的程序集

 services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

3. 建立映射类

新建CompanyProfile.cs Profile类

 public class CompanyProfile : Profile
    {
        public CompanyProfile()
        {
            CreateMap<Company, CompanyDto>()  // 映射
                .ForMember(			// 按照默认规则无法映射成功的
                    dest => dest.CompanyName,  // 目标属性 CompanyDto.CompanyName
                    opt => opt.MapFrom(src => 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);
}

以上是关于3AutoMapper In Asp.net Core的主要内容,如果未能解决你的问题,请参考以下文章

Three steps to use jQuery UI in ASP.NET MVC 5

Dependency Injection in ASP.NET Web API 2

in (ASP.NET) 之外的流利 NHibernate 错误映射程序集

ResolveUrl in external JavaScript file in asp.net project

CRUD Operations In ASP.NET MVC 5 Using ADO.NET

GraphQL in ASP.NET Core 系列视频 2 - 图论