EF 代码优先外键创建重复数据
我在使用代码优先外键时遇到了一些问题。我有一个如下所述的产品,我正在尝试使用该现有产品创建一个新的 LineItem。然而,当我将更改保存到上下文时,它会创建一个全新的产品,但它与我最初使用的产品重复,只是 id 是新的(现在数据库中的新记录)。
这是我添加新订单项的位置:
public void AddItem(Product item) {
// checking item.Id here will return 100
var lineItem = new LineItem
{
CartId = this.Id,
Product = item,
ProductId = item.Id,
Quantity = 1
};
_db.LineItems.Add(lineItem);
_db.SaveChanges();
// checking lineItem.Id here returns 101
// also checking item.Id here now also returns 101
this.LineItems.Add(lineItem);
}
public class LineItem {
[Key]
[Required]
public int Id { get; set; }
[Required]
public int CartId { get; set; }
[Required]
public int ProductId { get; set; }
[Required]
public int Quantity { get; set; }
[ForeignKey("CartId")]
public virtual Cart Cart { get; set; }
[ForeignKey("ProductId")]
public virtual Product Product { get; set; }
}
为什么要创建新产品?
I'm having some trouble with a Code-First ForeignKey. I have a Product as described below and I am trying to create a new LineItem with that existing Product. However when I save the changes to my context it creates an entirely new Product, but a duplicate of the one I originally used except that the id is new (new record in the db now).
Here's where I'm adding a new line item:
public void AddItem(Product item) {
// checking item.Id here will return 100
var lineItem = new LineItem
{
CartId = this.Id,
Product = item,
ProductId = item.Id,
Quantity = 1
};
_db.LineItems.Add(lineItem);
_db.SaveChanges();
// checking lineItem.Id here returns 101
// also checking item.Id here now also returns 101
this.LineItems.Add(lineItem);
}
public class LineItem {
[Key]
[Required]
public int Id { get; set; }
[Required]
public int CartId { get; set; }
[Required]
public int ProductId { get; set; }
[Required]
public int Quantity { get; set; }
[ForeignKey("CartId")]
public virtual Cart Cart { get; set; }
[ForeignKey("ProductId")]
public virtual Product Product { get; set; }
}
Why is it creating a new Product?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据评论,您正在使用产品对象的独立副本。因此,EF 在附加时将其视为一个新实例(通过
LineItem.Product
setter 中生成的代码并相应地插入它。您可以像这样重新附加您的实体
As per comments, you are using an unattached copy of your product object. So EF sees this as a new instance when it gets attached (via the generated code in the
LineItem.Product
setter and inserts it accordingly.You can re-attach your entity like so
问题的另一种解决方案可能是将与添加
Products
时使用的上下文相同的上下文传递给AddItem
方法。这样,您就可以确保用于
LineItems
的上下文不会被分离,并且 EF 不会认为需要添加Products
(或任何其他实体)重要)再一次。最好的问候,
阿迪·康斯坦丁
Another solution to your issue could be to pass the same context to the
AddItem
method as the one used where you've addedProducts
.This way you would be sure the the context used to
LineItems
wouldn't be detached, and EF would not see the need to add theProducts
(or any other entity for that matter) once more.Best regards,
Adi Constantin