asp.net-mvcentity-frameworkautomapperviewmodeleditmodel

Map EditModel using Automapper


I'm stuck trying to map ViewModel class using Automapper with classes listed below:

public class Product
{
    [Key]
    public int ProductId { get; set; }
    public string Name { get; set; }
    public ICollection<Color> Color { get; set; }
}

public class Color
{
    [Key]
    public int id { get; set; }
    public string value { get; set; }

    public virtual ICollection<Product> products { get; set; }
}

public class ProductVM
{
    [Key]
    public int ProductId { get; set; }
    public string Name { get; set; }
    public List<int> Color { get; set; }
    public IEnumerable<Color> Colors { get; set; } 
}

With Colors I pass all the available colors to the View for user to choose, and Color property to get the values, having something like this into the view:

@Html.ListBoxFor(model => Model.Color, new MultiSelectList(Model.Colors, "id", "value"));

Then in a contorller I've got a Post method, which saves it. I tryed to use Automapper to convert classes but it fails to map Color property as it should get the Color object by the available id.

Mapper.CreateMap<ProductVM, Product>();
Product product = AutoMapper.Mapper.Map<ProductVM, Product>(productVM);
db.Products.Add(product);
db.SaveChanges();

Am I missing somethig?


Solution

  • I tried something in my solution, colors will be null as the selectlist is not returned from the view. Your list of int's (color) will not be null and you can map this to the color object.

    var productVM = new ProductVM
    {
        Name = "Test",
        ProductId = 5,
        Colors = null,
        Color = new List<int> {1, 5, 8}
    };
    
    Mapper.CreateMap<int, Color>()
        .ForMember(dest => dest.id, opt => opt.MapFrom(src => src));
    
    Mapper.CreateMap<ProductVM, Product>()
        .ForMember(dest => dest.Color, opt => opt.MapFrom(src => src.Color));
    
    Product product = AutoMapper.Mapper.Map<ProductVM, Product>(productVM);
    db.Products.Add(product);
    db.SaveChanges();