Cleanest Way To Map Entity To DTO With Linq Select?

前端 未结 4 1977
梦如初夏
梦如初夏 2020-12-13 19:45

I\'ve been trying to come up with a clean and reusable way to map entities to their DTOs. Here is an example of what I\'ve come up with and where I\'m stuck.

4条回答
  •  遥遥无期
    2020-12-13 20:33

    You could either use AutoMapper or write extension methods like these:

    public static class PersonMapper
    {
        public static PersonDTO ConvertToDTO(this Person person)
        {
            return new PersonDTO { ID = person.ID, Name = person.Name, Address = person.Address.ConvertToDTO() };
        }
    
        public static IEnumerable ConvertToDTO(this IEnumerable people)
        {
            return people.Select(person => person.ConvertToDTO());
        }
    }
    
    public static class AddressMapper
    {
        public static AddressDTO ConvertToDTO(this Address address)
        {
            return new AddressDTO { ID = address.ID, City = address.City };
        }
    
        public static IEnumerable ConvertToDTO(this IEnumerable
    addresses) { return addresses.Select(address => address.ConvertToDTO()); } }

    You could then map a Person object to a PersonDTO object like this:

    public class Program
    {
        static void Main(string[] args)
        {
            Person person = new Person { ID = 1, Name = "John", Address = new Address { ID = 1, City = "New Jersey" } };
            PersonDTO personDTO = person.ConvertToDTO();
            Console.WriteLine(personDTO.Name);
        }
    }
    

提交回复
热议问题