将特定的接口实现映射到接口目标

问题描述 投票:0回答:1

我的AutoMapper配置文件中有几个映射,用于相同的源和目标类型。目标类型是一个具有几种具体实现的接口。根据情况,我将映射到IEmployeeDto的适当的具体实现。

// Model
public class Department
{
  public List<Employee> Employees { get; set; }
}

public class DepartmentDto
{
  public List<IEmployeeDto> Employees { get; set; }
}

public class EmployeeDto1 : IEmployeeDto 
{
  ...
}

public class EmployeeDto2 : IEmployeeDto
{
  ...
}

// Mappings
profile.CreateMap<Employee, IEmployeeDto>()
  .As<EmployeeDto1>();

profile.CreateMap<Employee, IEmployeeDto>()
  .As<EmployeeDto2>();

我也在使用实体框架。在运行时,我使用投影来映射:

var department = context.Departments
  .ProjectTo<DeparmentDto>(config)
  .SingleOrDefaultAsync(d => d.Name == departmentName);

//In this specific use case, I'm expecting EmployeeDto2 instead of EmployeeDto1
var employees = department.Employees;

是否有任何方法可以暗示应该将目标类型的具体实现映射到?

c# automapper
1个回答
0
投票

您通过指定已配置为使用特定类型的AutoMapper映射来“提示”应使用的具体实现。当你写

profile.CreateMap<Employee, IEmployeeDto>().As<EmployeeDto1>();

EmployeeDto1对象应映射到Employee实例时,它将使用特定的IEmployeeDto类。如果要使用其他映射,只需在AutoMapper配置中更改已配置的映射,或使用其他本身已配置了不同映射的AutoMapper配置。您可以具有MapperConfiguration对象的多个实例,每个实例都有其自己的配置。 ProjectTo()方法需要使用配置,因此您可以根据需要交换配置。

© www.soinside.com 2019 - 2024. All rights reserved.