【发布时间】:2019-01-25 04:26:39
【问题描述】:
我正在尝试向现有模型的 ICollection 添加值,但是当我下次尝试捕获它时,我的 ICollection 为空。
有我的代码和
型号:
public class OrderDetails
{
[Key]
public int OrderID { get; set; }
public int UserID { get; set; }
public DateTime OrderTime { get; set; }
public double Total { get; set; }
public virtual ICollection<Product> Cart { get; set; }
}
}
在我的 ICollection 中输入值:
OrderDetails order = new OrderDetails();
order.UserID = u.ID;
// I have tried this also:
//
// foreach(Product p in productsCollection)
//{
// order.Cart.Add(p);
//}
// the productsCollection is a List that contains values...
//
order.Cart = productsCollection; // this is my problem
order.OrderTime =DateTime.Now;
order.Total = sum;
_context.OrderDetails.Add(order);
_context.SaveChanges();
return Redirect("/Index");
尝试使用 OrderID 再次捕获它:
OrderDetails orderDetails = _context.OrderDetails
.Where(ood => ood.OrderID == 18)
.Include("Cart")
.FirstOrDefault();
有2个截图可以说明我的问题:
1) 购物车是空的: when trying to catch the cart:
2)同时dbcontext:
but when checking my dbcontext it contains the values:
** 请注意,有时购物车在计数中可能是 1、2 或 0 .. 我无法解释为什么以及何时发生这种情况。
【问题讨论】:
-
你能把你设置 productsCollection 变量的代码贴出来
标签: c# asp.net entity-framework linq .net-core