InvalidOperationException on Attaching POCO entity to context
I'm experiencing a trouble with attaching a POCO entity to its context. I'm getting an InvalidOperationException with the following message:
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
Actually, I only got this exception with a single item. I did not experience this kind of exception when I attached different items aside from this specific item.
I'm using the following code:
ItemDocument itemDocument = new ItemDocument();
Item item = GetItem(itemID); // the item I got here is detached
using (SampleContext context = new SampleContext()){
context.Items.Attach(item); // I got the exception here
context.LoadProperty(item, "Classifications");
itemDocument.Classification = item.Classifications.Select(c => c.Name).ToList开发者_开发百科();
}
Thanks.
What about trying to Detach
the old object from context before attaching new one with the same key?
精彩评论