Reputation: 407
I am trying to subtract the field "QtyOnHand" in the table "Inventory" from the quantity in List. But I get this error:
Unable to cast object of type 'System.Collections.Generic.List`1[System.Int32]' to type 'System.IConvertible'.
It shows that the error occurs at:
var cartQty = (from i in items where i.ProductId == Convert.ToInt32(productId) select i.Qty).SingleOrDefault();
My code is the following:
protected void btnCheckout_Click(object sender, EventArgs e)
{
int inventoryQty;
List<Item> items = Session["Cart"] as List<Item>;
using (ProjectEntities myEntities = new ProjectEntities())
{
var productId = (from i in items select i.ProductId).ToList();
var cartQty = (from i in items where i.ProductId == Convert.ToInt32(productId) select i.Qty).SingleOrDefault();
var inventory = (from q in myEntities.Inventories
where q.ProductId == Convert.ToInt32(productId)
select q).SingleOrDefault();
inventoryQty = inventory.QtyOnHand - cartQty;
myEntities.SaveChanges();
Response.Redirect("~/Home.aspx");
}
}
Thanks in advance!
Upvotes: 0
Views: 280
Reputation: 218722
var productId = (from i in items select i.ProductId).ToList();
productId
variable contains a list of items and you are trying to pass that to Convert.ToInt32
to method which is not expecting a collection of items!. That is causing the issue.
Since you are cart may have more than one item, you probably need to loop throug the productIds and do your other calculation.
var productIdList = (from i in items select i.ProductId).ToList();
foreach(var productId in productIdList)
{
var cartQty = (from i in items where i.ProductId == Convert.ToInt32(productId)
select i.Qty).SingleOrDefault();
// Your remaining code
}
I am assuming the productId in your cart item is of numeric value, but of string type. Then only the Convert.ToInt32
will work as it is expecting the string representation of some valid numeric value (Ex :"234"
)
If it is of int type, you do not need the Convert.ToInt32(productId)
part in your where clause, just use i.ProductId==productId
Upvotes: 1