实体框架:更新连接表 [英] Entity Framework: Updating join tables
本文介绍了实体框架:更新连接表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有如下表设置:
- 订单(ID)
- 产品(ID),其中的ProductID 1和2已经存在]
- OrderProduct (订单ID,产品ID)两个键FK'ng以订单和产品表]
- Order (ID)
- Product (ID) [where ProductID 1 and 2 already exist]
- OrderProduct (OrderId, ProductID) [two keys FK'ng to Order and Product tables]
和我'试图将记录添加到订单表中指派2产品中的顺序如下:
And I'am trying to add a record to Order table assigning 2 products in to the order as follows:
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:
You should use db instead of creating new Product, like in this example:
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);
这篇关于实体框架:更新连接表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文