首页 > 解决方案 > 如何将整数转换为模型类型?

问题描述

在这里,我试图从表格Product列中显示所有购物车项目以及相应的库存项目InStock
为了获取购物车中每件商品的库存编号,我对每件商品都使用了 foreach,并尝试将编号添加到购物车中。

现在,cart.Add(item.InStock);foreach 里面的 line 有问题"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; }
}

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

解决方案


由于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方法 ofList<CartVM>因为item类型为List<Product>,因此您需要使用CartVM实例并从那里分配其属性。


推荐阅读