在常见的DTO类中重用通用映射代码

时间:2014-04-24 04:31:59

标签: c# code-reuse

我有2个DTO类,它们具有多个常见属性,我试图避免在为实体编写映射代码到DTO转换时不得不重复自己,我想知道如何实现这一点,我有感觉我需要使用FuncAction委托来实现这一目标。例如,我有2个类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; }
}

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

2 个答案:

答案 0 :(得分:1)

使用图书馆..这就是他们的目的!

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

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

..然后当你想要映射时:

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

答案 1 :(得分:1)

你可能会做这样的事情(非常基本但不优雅): (注意实体当然可以是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;
    }
}
相关问题