简体   繁体   中英

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?

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM