1

我一直在尝试使用 Automapper 将 ViewModel 类与下面列出的类进行映射:

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

使用颜色,我将所有可用颜色传递给视图供用户选择,并使用 Color 属性获取值,在视图中具有如下内容:

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

然后在一个控制器中,我有一个 Post 方法,可以保存它。我尝试使用 Automapper 转换类,但它无法映射 Color 属性,因为它应该通过可用的 id 获取 Color 对象。

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

我错过了什么吗?

4

2 回答 2

1

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();
于 2015-07-31T12:08:07.813 回答
0

发生这种情况是因为 Automapper 不知道如何从 List< int > Color 映射到 ICollection< Color > Colors。尝试为此创建地图。

Mapper.CreateMap<SourceObject, TargetObject>();
Mapper.CreateMap<SourceOuterObject, TargetOuterObject>()
    .ForMember(dest => dest.TargetList, opt => opt.MapFrom(src => src.SourceSet.SourceList);
于 2015-07-31T11:53:28.067 回答