Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 215
Sachin Parashar Avatar asked Nov 26 '25 19:11

Sachin Parashar


1 Answers

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());
like image 168
Lucian Bargaoanu Avatar answered Nov 29 '25 07:11

Lucian Bargaoanu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!