c# - 如何将整数转换为模型类型?
问题描述
在这里,我试图从表格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; }
}
解决方案
由于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
实例并从那里分配其属性。
推荐阅读
- javascript - HTML5 视频海报图像横向显示
- spring-cloud-config - 使用 HTTPS 凭证连接 Spring Cloud Config 和 AWS Code Commit
- javascript - jQuery 与附加数据交互
- xslt - 排序后如何使用XSL获取第一个孩子
- python - JSONDecodeError:期望值:执行大型 API 请求时的第 1 行第 1 列(字符 0)
- android - Android SQLite SELECT SUM 按特定列过滤
- java - 使用GMM和EM算法进行图像分割java
- c# - visual studio 2015 警告:无法读取与解决方案关联的某些属性
- javascript - 在 chrome 扩展中加载特定页面时创建弹出对话框
- excel - VBA-一个定时器功能,一步一步地捕捉经过的时间