user1765862
user1765862

Reputation: 14145

AutoMapper custom resolver on the child type

public class Car
{
    public int Id {get;set;}
    public string Name {get;set;}
    public Owner OwnerData {get;set}
}

public class Owner
{
    public int Id {get;set;}
    public string Name {get;set;}
    public string Phone {get;set;}
}


public class CarProfile : Profile
{
    public CarProfile()
    {
        CreateMap<Car, Owner>()
          .ForMember(m => m.OwnerData.Name, o=>o.MapFrom(p=>p.Name));
    }
}

Owner ownerData = repository.Get<Owner>(id);
IEnumerable<Car> data = mapper.Map<IEnumerable<Car>>(ownerData);

"ClassName": "System.ArgumentException", "Message": "Expression 'm => m.OwnerData.Name' must resolve to top-level member and not any child object's properties. You can use ForPath, a custom resolver on the child type or the AfterMap option instead.",

How can I map this?

Upvotes: 1

Views: 4566

Answers (2)

omri tsufim
omri tsufim

Reputation: 57

You are using ForMember but setting a child member of Owner. replace ForMember with ForPath and it should work

CreateMap<Car, Owner>()
    .ForPath(m => m.OwnerData.Name, o=>o.MapFrom(p=>p.Name));

Upvotes: 4

Ciobanu Cristian
Ciobanu Cristian

Reputation: 34

This won't work because you are using 2 level in the dest lambda.

With Automapper, you can only map to 1 level. To fix the problem you need to use a single level.

CreateMap<Owner, Car>().ForMember(dest => dest.OwnerData,
         input => input.MapFrom(i => new Owner { Name = i.Name })); 

Upvotes: 1

Related Questions