How to automap this(mapping sub members)

2020-04-02 09:15发布

问题:

I have something like this

public class ProductViewModel
{
  public int SelectedProductId { get; set; }
  public string ProductName {get; set;}
  public int Qty {get; set;}
   public List<SelectListItem> Products { get; set}; 
}

I have a domain like this

public class Product
{
  public int ProductId {get; set;}
  public string ProductName {get; set;}
  public int Qty {get; set;}
}


public class Store
{
  public Product() {get; set;}
}

Now I need to do the mapping.

// in my controller

var result = Mapper.Map<ProductViewModel, Store>(Product);

this won't bind anything since it can't figure out how to put the ProductId in since it is

Store.Product.ProductId;

My map is like this

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

I get this error

Expression 'dest => Convert(dest.Product.SelectedProductId' must resolve to top-level member. Parameter name: lambdaExpression

I am unsure how to do this.

回答1:

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.



回答2:

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


回答3:

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



回答4:

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.