3、AutoMapper 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);
}

posted @ 2020-05-14 23:15  乾子  阅读(221)  评论(0编辑  收藏  举报