In Entity Framework, is it possible to see whether an object has previously been associated to a data context?

.net entity-framework


When attempting to connect an object that is already tied to a certain context through, I keep receiving the following error.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 to do anything like this:




Although similar, Jason's extension strategy doesn't apply to my circumstances.

I'm attempting to do some work following the strategy described in the response to another query.

How can I use Linq to Entities to remove one or more rows from my database *without* initially fetching them?

My code is something similar to this:

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

Everything is great up to the point when I attempt to connect a fake using the same approach for that user.User object. I already connected the fake user object, hence this doesn't work. How can I be sure of this?

5/23/2017 11:47:06 AM

Accepted Answer

What I came up with, which works very well, is as follows:

public static void AttachToOrGet<T>(this ObjectContext context, string entitySetName, ref T entity)
    where T : IEntityWithKey
    ObjectStateEntry entry;
    // Track whether we need to perform an attach
    bool attach = false;
    if (
                context.CreateEntityKey(entitySetName, entity),
                out entry
        // Re-attach if necessary
        attach = entry.State == EntityState.Detached;
        // Get the discovered entity to the ref
        entity = (T)entry.Entity;
        // Attach for the first time
        attach = true;
    if (attach)
        context.AttachTo(entitySetName, entity);

It may be referred to as follows:

User user = new User() { Id = 1 };
II.AttachToOrGet<Users>("Users", ref user);

This is incredibly effective since it's similar tocontext.AttachTo(...) except that you can always use the ID method I mentioned before. Either the item that was previously connected or your own object is ultimately attached. CallingCreateEntityKey Make sure the context is good and general and will operate without further code even with composite keys (since EF can already do it for us!).

11/11/2009 3:54:16 PM

Popular Answer

An easier strategy is:

 bool isDetached = context.Entry(user).State == EntityState.Detached;
 if (isDetached)

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