使用实体框架将现有实体添加到新创建的实体的集合中 [英] Using the entity framework to add existing entities to a collection on a newly created entity
问题描述
我正在使用实体框架创建新的订单。该订单包含一个联系人的集合,一对多关系。我想在订单创建时添加对现有联系人的引用。订单和联系实体对象。
I am using the Entity framework to create a new order. The order contains a collection of contacts, a many to many relationship. I want to add a reference to an existing contact on the order on creation of the order. Both Order and Contact a Entity Objects.
Order order = new Order();
//set details on order
Contact contact = new Contact();
EntityKey contactKey =
new EntityKey("OrderDetails.Contact",
"contact_id", contact.Key.Id);
contact.EntityKey = contactKey;
contact.contact_id = contact.Key.Id;
order.Contact.Attach(contact); // throws an exception!
OrderDetails ordTable = new OrderDetails();
ordTable.AddToOrder(order);
int result = orgTable.SaveChanges();
当我去附加时,抛出这个异常:
When I go to attach, this exception is thrown:
当与此相关端相关联的源对象处于添加,删除或分离状态时,附加不是有效的操作。使用NoTracking合并选项加载的对象总是分离。
"Attach is not a valid operation when the source object associated with this related end is in an added, deleted, or detached state. Objects loaded using the NoTracking merge option are always detached."
我知道我可能错过了一个步骤,或者完全不了解实体框架如何处理多对多关系。
I know I'm probably missing a step or not fully understanding how the entity framework handles many-to-many relationships.
推荐答案
附件是不允许的,因为您尚未保存订单。调用添加告诉实体框架您要插入新的联系人。所以你只剩一个选项。您需要加载联系人。
"Attach" is not allowed because you haven't saved the order yet. Calling "Add" tells Entity Framework that you want to insert a new contact. So you are left with only one option. You need to load the contact.
这是最快的方法:
OrderDetails context = new OrderDetails();
Contact contact = context.GetObjectByKey(new EntityKey("OrderDetails.Contact", "contact_id", existingContactId));
order.Contact.Add(contact);
这篇关于使用实体框架将现有实体添加到新创建的实体的集合中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!