Adding existing entities to a collection on a newly built object using the entity framework

entity-framework many-to-many


In order to make a new order, I'm utilizing the Entity framework. A number of contacts are included in the sequence, forming a many-to-many link. When I create the order, I want to include a reference to an existing contact. Order and Contact an Entity Objects both exist.

 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();
            int result = orgTable.SaveChanges();

The following exception is raised when I try to attach:

"When the source object connected to this linked end is in an added, destroyed, or detached state, attach is not a legal action. The NoTracking merge option always detaches the loaded objects."

I'm aware that I'm probably not using the entity framework correctly or that I don't completely get how it manages many-to-many connections.

1/2/2009 6:56:00 PM

Popular Answer

"Attach" is not permitted since the order has not yet been stored. By using "Add," you may instruct Entity Framework to add a new contact. Therefore, you are only left with one choice. The contact has to be loaded.

The quickest approach to achieve it is as follows:

OrderDetails context = new OrderDetails();
Contact contact = context.GetObjectByKey(new EntityKey("OrderDetails.Contact", "contact_id", existingContactId));
12/16/2009 5:16:33 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow