简体   繁体   中英

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?

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

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

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