如何使用嵌套的opbjects使用DBContext.Add / Attach(使用EF CodeFirst 4.1) [英] How to use DBContext.Add/Attach (using EF CodeFirst 4.1) with nested opbjects
问题描述
示例:
数据库包含0个订单和3个项目。
我添加一个订单2项目。
现在数据库保存1个订单,5个项目。订单中的两个项目已经被读取到数据库,即使这些项目在db.SaveChanges()之前具有正确的主键。
我意识到我可能可以在保存更改之前将现有项目附加到dbcontext,但那真的是唯一的办法吗?当主键与现有项目匹配时,EF不能确定项目已经存在?
有没有人知道新版本的EF CodeFirst是否有所不同?
否 你必须确定正确图中每个实体的状态,例如使用: 您可以使用反向操作调用 Problem: When adding an object "Order" to my dbcontext, all nested objects of the order gets "readded" to the database, though the nested objects is static data and only a reference shoudl be added in the database. Example:
The database holds 0 orders, and 3 items. I add one order with 2 items. Now the database hold 1 order, and 5 items. The two items in the order has been "readded" to the database, even though the items had the right primary keys before db.SaveChanges(). I realize that i may be able to attach the existing items to the dbcontext before saving changes, but is that really the only way to go? Can't EF figure out that to item already exists when the primary key matches an existing item? Does anyone know if this is different in the new version of EF CodeFirst? No EF cannot figure if entities are existing one or new one - both Add and Attach commands are graph oriented operations. You call them on one entity in the graph and they traverse all relations (and their relations and so on) and perform the operation for them as well. You must figure correct state of each entity in the graph for example by using: You can use the reverse operation by calling 这篇关于如何使用嵌套的opbjects使用DBContext.Add / Attach(使用EF CodeFirst 4.1)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
dbContext.Orders.Add(newOrder);
foreach(newOrder.Items中的var item){
dbContext.Entry(item).State = EntityState.Unchanged;
}
dbContext.SaveChanges();
Attach(newOrder)
并将顺序设置为添加
状态。主要区别在于独立关联 (例如多对多关系)。第一种方法将在订单和每个项目之间正确添加新关系,而第二种方法除非您手动将每个关系设置为添加
状态(并且关系更改状态更复杂)。 dbContext.Orders.Add(newOrder);
foreach(var item in newOrder.Items) {
dbContext.Entry(item).State = EntityState.Unchanged;
}
dbContext.SaveChanges();
Attach(newOrder)
and set the order to Added
state. The main difference will come with independent associations (for example many-to-many relations). The first approach will correctly add new relation between order and each item whereas second will not unless you manually set each relation to Added
state (and changing state for relations is more complex).