[英]An entity object cannot be referenced by multiple instances of IEntityChangeTracker. in entity framework
[英]An entity object cannot be referenced by multiple instances of IEntityChangeTracker. with EF6
这些是我的课
public class Bill
{
[Key]
public int BillID { get; set; }
[Required]
public int BillNumber { get; set; }
[Required]
public DateTime Date { get; set; }
[Required]
public string UserName { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Adress { get; set; }
[Required]
public string PostalCode { get; set; }
[Required]
public string City { get; set; }
[Required]
public string Country { get; set; }
public Bill()
{
Date = new DateTime();
Date = DateTime.Now;
}
public class Cart
{
[Key]
public int CartID { get; set; }
[Required]
public int BillID { get; set; }
[Required]
[ForeignKey("BillID")]
public virtual Bill Bill { get; set; }
public virtual ICollection<CartItems> Products {get; set;}
}
public class CartItems
{
[Key]
public int CartItemID { get; set; }
[Required]
public Product Product { get; set; }
[Required]
public int Qunatity { get; set; }
}
}
我正在构建一个ASP.NET 4 Web应用程序。 我想在购物车中添加产品时遇到问题,它会引发错误
IEntityChangeTracker的多个实例不能引用一个实体对象。
当我想在上下文中向购物车添加购物车对象时。
Bill bill = new Bill();
bill.BillNumber = Bill.GetLastBillNumber(context) + 1;
bill.Adress = txtAdress.Text;
bill.City = txtCity.Text;
bill.Country = ddlCountry.SelectedItem.Value.ToString();
bill.Name = txtName.Text;
bill.PostalCode = txtPostalCode.Text;
bill.UserName = lblUserName.Text;
context.Bills.Add(bill);
context.SaveChanges();
Cart cart = new Cart();
cart.Bill = bill;
cart.BillID = bill.BillID;
cart.Products = Application["CartProducts"] as List<CartItems>;
context.Carts.Add(cart);
context.SaveChanges();
我读到有关该问题的信息,但我无法完成它对我不起作用的工作;
DataContext在类中定义为privet
private DataContext context = new DataContext();
如果有人可以帮助我。
谢谢。
您是否通过其他上下文将产品加载到其他地方的Application[CartProducts]
中? 在那种情况下就是问题所在。
DataContext
是工作单元的实现,这意味着您在单个操作中所做的所有工作都必须在同一上下文中完成。
虽然缓存产品通常是一个好主意,但它不起作用。 您将不得不在列表中创建对象的副本。
cart.Products = (Application["CartProducts"] as List<CartItems>).Select(ci =>
CartItem { ProductId = ci.ProductId, Quantity = ci.Quantity }).ToList();
请注意,我已经用ProductId
替换了Product
,以避免不得不再进入对象树一级。 在数据库中,对象之间的引用将作为外键实现,并且通过将其映射到ProductId
您将能够访问它并直接使用它。 有关映射外键的详细信息,请参见我的博客文章 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.