3

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?

4
  • Works for me, try upgrading. Commented Apr 1, 2019 at 11:46
  • @LucianBargaoanu I have the latest 6.0.0 version of Automapper.Extensions.Microsoft.DependencyInjection Commented Apr 1, 2019 at 11:49
  • Most likely your configuration is ignored because you're not setting it up properly. Check the docs. Commented Apr 1, 2019 at 12:23
  • @LucianBargaoanu Configuration seems fine because I changed property "Name" to "CompanyName" and updated configuration .ForMember(dest => dest.CompanyName, opt => opt.MapFrom(src => src.Value)) And it worked. Commented Apr 1, 2019 at 12:39

1 Answer 1

3

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());
Sign up to request clarification or add additional context in comments.

4 Comments

You are absolutely right. I was just trying the same in a new dummy project without that constructor and it worked.
Actually, I don't need that constructor anymore. So, I removed that and it's working as expected now. Thanks a lot @Lucian
The parameter in the lambda expression should be dest for not creating confusion: ConstructUsing(dest => new ViewCompany());
Actually no :) You receive the source and you return the destination.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.