这些是我的课
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();
如果有人可以帮助我,请。
谢谢。