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

时间:2019-02-21 07:04:30

标签: c# asp.net-mvc-5

在这里,我试图显示表ProductInStock中所有购物车项目以及相应的库存项目。
为了获取购物车中每件商品的库存编号,我为每个商品分别使用foreach并尝试将其添加到购物车中。

现在,在cart.Add(item.InStock);内的foreach说"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;
    }



下面是模型类

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

1 个答案:

答案 0 :(得分:0)

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

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分配给Add的{​​{1}}方法,因为List<CartVM>的类型为item,因此您需要使用{{1 }}实例并从那里分配其属性。