[英]Entity Framework: Updating join tables
I have following table setup: 我有以下表格设置:
And I'am trying to add a record to Order table assigning 2 products in to the order as follows: 我试图在Order表中添加一条记录,将2个产品分配到订单中,如下所示:
var order = new Order();
order.Products.Add(new Product {ID=1});
order.Products.Add(new Product {ID=2});
db.SaveChanges();
The problem is: When saving the order, two Products are getting inserted in to the DB, instead of referring to the product records that already exists. 问题是:保存订单时,会将两个产品插入到DB中,而不是引用已存在的产品记录。
Please help. 请帮忙。 Thanks. 谢谢。
You should use db instead of creating new Product, like in this example: 您应该使用db而不是创建新Product,如下例所示:
var order = new Order();
order.Products.Add(db.Products.First(p => p.ID = 1));
order.Products.Add(db.Products.First(p => p.ID = 2));
db.SaveChanges();
Or, you need to "Update Reference" after product creation. 或者,您需要在创建产品后“更新参考”。 you can do something like this: 你可以这样做:
var product = new Product() { ID = 1 };
db.Attach(product);
order.Products.Add(product);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.