使用实体框架将现有实体添加到新创建的实体上的集合中

时间:2021-07-10 23:13:47

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.

我正在使用Entity框架来创建新订单。该订单包含一系列联系人,多对多关系。我想在创建订单时添加对订单上现有联系人的引用。订购和联系实体对象。

 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:

当我去附加时,抛出此异常:

"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."

“当与此相关端相关联的源对象处于添加,删除或分离状态时,附加不是有效操作。使用NoTracking合并选项加载的对象始终是分离的。”

I know I'm probably missing a step or not fully understanding how the entity framework handles many-to-many relationships.

我知道我可能错过了一步或者没有完全理解实体框架如何处理多对多关系。

2 个解决方案

#1


"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.

不允许“附加”,因为您尚未保存订单。调用“添加”会告知实体框架您要插入新联系人。所以你只剩下一个选择。您需要加载联系人。

Here's the fastest way to do that:

这是最快的方法:

OrderDetails context = new OrderDetails();
Contact contact = context.GetObjectByKey(new EntityKey("OrderDetails.Contact", "contact_id", existingContactId));
order.Contact.Add(contact);

#2


If Order has a property Contact, then you can do:

如果Order有一个属性Contact,那么你可以这样做:

order.Contact.Add(contact);

I would suggest making the property called Contacts rather than Contact, though.

我建议将该属性称为Contacts而不是Contact。

#1


"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.

不允许“附加”,因为您尚未保存订单。调用“添加”会告知实体框架您要插入新联系人。所以你只剩下一个选择。您需要加载联系人。

Here's the fastest way to do that:

这是最快的方法:

OrderDetails context = new OrderDetails();
Contact contact = context.GetObjectByKey(new EntityKey("OrderDetails.Contact", "contact_id", existingContactId));
order.Contact.Add(contact);

#2


If Order has a property Contact, then you can do:

如果Order有一个属性Contact,那么你可以这样做:

order.Contact.Add(contact);

I would suggest making the property called Contacts rather than Contact, though.

我建议将该属性称为Contacts而不是Contact。