简体   繁体   中英

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?

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();

This is happening because Automapper doesn't know how to map from List< int > Color to ICollection< Color > Colors. Try creating a map for this also.

Mapper.CreateMap<SourceObject, TargetObject>();
Mapper.CreateMap<SourceOuterObject, TargetOuterObject>()
    .ForMember(dest => dest.TargetList, opt => opt.MapFrom(src => src.SourceSet.SourceList);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM