Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is is possible to check if an object is already attached to a data context in Entity Framework?

I am getting the following error when trying to attach an object that is already attached to a given context via context.AttachTo(...):

An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

Is there a way of achieving something along the lines of:

context.IsAttachedTo(...)

Cheers!

Edit:

The extension method Jason outlined is close, but it doesn't work for my situation.

I am trying to do some work using the method outlined in the answer to another question:

How do I delete one or more rows from my table using Linq to Entities *without* retrieving the rows first?

My code looks a bit like this:

var user = new User() { Id = 1 }; context.AttachTo("Users", user); comment.User = user; context.SaveChanges(); 

This works fine, except when I do something else for that user where I use the same method and try to attach a dummy User object. This fails because I have previously attached that dummy user object. How can I check for this?

like image 663
joshcomley Avatar asked Nov 11 '09 14:11

joshcomley


1 Answers

A simpler approach is:

 bool isDetached = context.Entry(user).State == EntityState.Detached;  if (isDetached)      context.Users.Attach(user); 
like image 130
Mosh Avatar answered Oct 04 '22 06:10

Mosh