Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to automap this(mapping sub members)

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.

like image 560
chobo2 Avatar asked Feb 08 '11 00:02

chobo2


1 Answers

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; }
}
like image 141
duyker Avatar answered Sep 21 '22 14:09

duyker