Gleb Skripnikov
Gleb Skripnikov

Reputation: 301

Same mapping for two different types using Automapper

Let's imagine I have classes UserInfoDto, UserDto and User

//Dto
public class UserInfoDto
{
     public string UserName {get; set;}
     public DateTime DoB {get; set;}
}

//Another Dto
public class UserDto
{
     public string Name {get; set;}
     public DateTime DateOfBirth {get; set;}
}

//DB model
public class User
{
     public string Name {get; set;}
     public DateTime DateOfBirth {get; set;}
}

And I want to create 2 mappings:

  1. From UserInfoDto to UserDto

  2. From UserInfoDto to User

     CreateMap<UserInfoDto, UserDto>()
         .ForMember(d => d.Name, opt => opt.MapFrom(s => s.UserName))
         .ForMember(d => d.DateOfBirth, opt => opt.MapFrom(s => s.DoB))
    
     CreateMap<UserInfoDto, User>()
         .ForMember(d => d.Name, opt => opt.MapFrom(s => s.UserName))
         .ForMember(d => d.DateOfBirth, opt => opt.MapFrom(s => s.DoB))
    

As you can see I have two identical mappings. Is there a way to create only one mapping (for example first one) and reuse the settings of this mapping for the second case?

I'm asking because in real-world code I have 20+ properties and I want to avoid duplication somehow.

Upvotes: 1

Views: 1393

Answers (1)

kosist
kosist

Reputation: 3057

If your properties have same names, there is no need to explicitly map them. It is enough to do the following:

CreateMap<UserInfoDto, UserDto>();
CreateMap<UserInfoDto, User>();

So Automapper will map properties by their names by itself.

Upvotes: 1

Related Questions