How to automap this(mapping sub members)

前端 未结 4 1964
春和景丽
春和景丽 2021-01-17 13:52

I have something like this

public class ProductViewModel
{
  public int SelectedProductId { get; set; }
  public string ProductName {get; set;}
  public int          


        
相关标签:
4条回答
  • 2021-01-17 14:10

    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; }
    }
    
    0 讨论(0)
  • 2021-01-17 14:11

    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.

    0 讨论(0)
  • 2021-01-17 14:11

    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.

    0 讨论(0)
  • 2021-01-17 14:15

    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 ...

    0 讨论(0)
提交回复
热议问题