跨公共DTO类重用公共映射代码

本文关键字:映射 代码 DTO | 更新日期: 2023-09-27 17:59:39

我有两个DTO类,它们有多个公共属性,我试图避免在编写实体到DTO转换的映射代码时重复自己的操作,我想知道如何实现这一点,我觉得我可能需要使用FuncAction委托来实现这一目标。例如,我有两个类StudentDTOEmployeeDTO:

public class StudentDTO : PersonDTO
{
    public int CourseId { get; set; }
    //other properties
}
public class EmployeeDTO : PersonDTO
{
    public int OccupationId { get; set; }
    //other properties
}

两者都自然地继承了PersonDTO:

public class PersonDTO
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string FamilyName { get; set; }
    public int Age { get; set; }
}

如何重用映射公共属性的映射代码?谢谢

跨公共DTO类重用公共映射代码

您可能可以做这样的事情(非常基本而不优雅):(注意,实体可以是DataReader、DataSet等)

public class Entity
{
    public string FirstName { get; set; }
    public string FamilyName { get; set; }
    public int CourseId { get; set; }
    public int OccupationId { get; set; }
}
public class BaseDto
{
}
public class PersonDto : BaseDto
{
    public string FirstName { get; set; }
    public string FamilyName { get; set; }
    public static void Map(Entity entity, PersonDto personDto)
    {
        personDto.FirstName = entity.FirstName;
        personDto.FamilyName = entity.FamilyName;
    }
}
public class StudentDto : PersonDto
{
    public int CourseId { get; set; }
    public static StudentDto Map(Entity entity)
    {
        var studentDto = new StudentDto { CourseId = entity.CourseId };
        // ..can call map to PersonDto if you want
        return studentDto;
    }
}
public class EmployeeDto : PersonDto
{
    public int OccupationId { get; set; }
    public static EmployeeDto Map(Entity entity)
    {
        var employeeDto = new EmployeeDto() { OccupationId = entity.OccupationId };
        // ..can call map to PersonDto if you want
        return employeeDto;
    }
}

public class Mapper<TDto>
    where TDto : BaseDto
{
    private TDto _dto;
    private readonly Entity _entity;
    public Mapper(Entity entity)
    {
        _entity = entity;
    }
    public Mapper<TDto> Map(Func<Entity, TDto> map)
    {
        _dto = map(_entity);
        return this;
    }
    public Mapper<TDto> Map<TBaseDto>(Action<Entity, TBaseDto> map)
        where TBaseDto : BaseDto
    {
        map(_entity, _dto as TBaseDto);
        return this;
    }
    public TDto Result
    {
        get { return _dto; }
    }
}
class Program
{
    static void Main(string[] args)
    {
        var studentEntity = new Entity() { FirstName = "John", FamilyName = "Doe", CourseId = 1 };
        var studentDto = new Mapper<StudentDto>(studentEntity)
            .Map(StudentDto.Map)
            .Map<PersonDto>(PersonDto.Map)
            .Result;
    }
}

使用库。。这就是他们在那里的目的!

  • 自动映射器
  • ValueInjecter

在Automapper中,您的上述映射变得非常简单:

Mapper.CreateMap<EmployeeDTO, StudentDTO>();
Mapper.CreateMap<StudentDTO, EmployeeDTO>();

然后当你想绘制地图时:

var studentInstance = ...; // go get student instance
var employee = Mapper.Map<Employee>(studentInstance);