Sachin Parashar
Sachin Parashar

Reputation: 1116

Map fields with same name to different fileds in automapper

I have a model which I am trying to map from Match class in .net core 2.0. Both the classes have a Name property.

I need to map Match.Value => ViewCompany.Name

But it always puts Match.Name into ViewCompany.Name

Here is my AutomapperProfile:

CreateMap<Match, ViewCompany>()
                .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Value));

.ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Value))

ViewCompany:

public class ViewCompany
{
    public ViewCompany()
    {

    }

    public ViewCompany(string name)
    {
        this.Name = name;
    }

    public int Id { get; set; }

    public string Name { get; set; }
}

The above mapping doesn't work.

But if I change property name in the model to something else like "Value" or "tempName" and update the automapper profile, it works fine.

So, is it not possible to map properties with same names to different properties in Automapper?

Upvotes: 3

Views: 3158

Answers (1)

Lucian Bargaoanu
Lucian Bargaoanu

Reputation: 3516

What happens here is that Name is mapped through the constructor. A simple way to avoid that is to tell AM what constructor to use:

 CreateMap<Match, ViewCompany>().ConstructUsing(source=>new ViewCompany());

Upvotes: 3

Related Questions