How to automap this(mapping sub members)

大城市里の小女人 提交于 2019-12-01 15:24:20

The error your getting is because you cannot declare mapping declarations more than one level deep in your object graph.

Because you've only posted one property its hard for me to give you the codes that will make this work. One option is to change your viewmodel property to MyTestTestId and the conventions will automatically pick up on that.

To Map nested structures, you just need to create a new object in the MapFrom argument.

Example

Mapping:

Mapper.CreateMap<Source, Destination>()
      .ForMember(d => d.MyNestedType, o => o.MapFrom(t => new NestedType { Id = t.Id }));
Mapper.AssertConfigurationIsValid();

Test Code:

var source = new Source { Id = 5 };
var destination = Mapper.Map<Source, Destination>(source);

Classes:

public class Source
{
    public int Id { get; set; }
}

public class Destination
{
    public NestedType MyNestedType { get; set; }
}

public class NestedType
{
    public int Id { get; set; }
}

You can use Resolver.

Create a resolver class like that :

class StoreResolver : ValueResolver<Store, int>
{
    protected override int ResolveCore(Store store)
    {
        return store.Product.ProductId;
    }
}

And use it like that :

Mapper.CreateMap<ProductViewModel, Store>()
        .ForMember(dest => dest.SelectedProductId, opt => opt.ResolveUsing<StoreResolver >());

Hope it will help ...

Kevat Shah

The correct answer given by allrameest on this question should help: AutoMapper - Deep level mapping

This is what you need:

Mapper.CreateMap<ProductViewModel, Store>()
    .ForMember(dest => dest.Product, opt => opt.MapFrom(src => src));
Mapper.CreateMap<ProductviewModel, Product>()
    .ForMember(dest => dest.ProductId, opt => opt.MapFrom(src => src.SelectedProductId));

NOTE: You should try to move away from using Mapper.CreateMap at this point, it is obsolete and will be unsupported soon.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!