以下にリストされているクラスで 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; }
}
Colors を使用して、使用可能なすべての色をビューに渡してユーザーが選択できるようにし、 Color プロパティを使用して値を取得し、次のようなものをビューに入れます。
@Html.ListBoxFor(model => Model.Color, new MultiSelectList(Model.Colors, "id", "value"));
次に、コントローラに、それを保存する Post メソッドがあります。Automapper を使用してクラスを変換しようとしましたが、使用可能な ID で Color オブジェクトを取得する必要があるため、Color プロパティのマッピングに失敗しました。
Mapper.CreateMap<ProductVM, Product>();
Product product = AutoMapper.Mapper.Map<ProductVM, Product>(productVM);
db.Products.Add(product);
db.SaveChanges();
何か不足していますか?