如何将整数转换为模型类型?

How to convert integer to model type?

我在这里尝试显示所有购物车商品以及 table ProductInStock 中的相应库存商品。
为了获取购物车中每件商品的库存编号,我对每件商品都使用了 foreach 并尝试将该编号添加到购物车。

现在,在 foreach 中的 cart.Add(item.InStock); 行有问题说 "Cannot convert from int? to eMedicine.Model.ViewModel.CartVM".

下面是我的代码

 public List<CartVM> ShoppingCartOrderList()
    {
        var cart = Session["cart"] as List<CartVM> ?? new List<CartVM>();
        var stockList = uow.Repository<Product>().GetAll().ToList();
        foreach (var item in stockList)
        {
            cart.Add(item.InStock); //error is in this line saying "Cannot convert from int? to eMedicine.Model.ViewModel.CartVM"
        }                       
        return cart;
    }



以下是型号 class

public class CartVM
{
    public int ProductId { get; set; }
    public string ProductName { get; set; }
    public int Quantity { get; set; }
    public decimal? ProductPrice { get; set; }
    public decimal? Total { get { return Quantity * ProductPrice; } }
    public int? Instock { get; set; }
    public string ImageName { get; set; }
    public string ProdcutManufacturer { get; set; }
    public string ProductDescription { get; set; }
    public string ProductComposition { get; set; }
    public string ProductCode { get; set; }

    public List<ProductGallery> ProductGalleries;
}

public partial class Product
{
    public int PId { get; set; }
    public string PName { get; set; }
    public Nullable<decimal> Price { get; set; }
    public Nullable<int> IsPrescriptionRequired { get; set; }
    public Nullable<int> InStock { get; set; }
    public string PImage { get; set; }
    public Nullable<int> IsNew { get; set; }
    public string ProductDescription { get; set; }
    public string Manufacturer { get; set; }
    public string ProductCode { get; set; }
    public string ProductComposition { get; set; }
}

由于 cart 包含 List<CartVM> 的实例,您必须使用 new CarVM() 无参数构造函数来分配具有 Nullable<int> 类型的 Instock 属性像这样:

var cart = Session["cart"] as List<CartVM> ?? new List<CartVM>();
var stockList = uow.Repository<Product>().GetAll().ToList(); // the type is List<Product>

foreach (var item in stockList)
{
    cart.Add(new CartVM() 
             {
                 // other properties
                 Instock = item.InStock 
             });
}

return cart;

请注意,您不能将 item 直接分配给 List<CartVM>Add 方法,因为 item 的类型为 List<Product>,因此您需要使用 CartVM 实例并从那里分配其属性。