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?
A simpler approach is:
bool isDetached = context.Entry(user).State == EntityState.Detached; if (isDetached) context.Users.Attach(user);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With