EntityFramework Code First - Check if Entity is attached

Radu Negrila picture Radu Negrila · Apr 5, 2012 · Viewed 29.8k times · Source

I am trying to update an entity with a FK relationship in EntityFramework 4.3 Code First. I try to attach to the related entites by calling: Entry(item).State = EntityState.Unchanged

I get the following exception: An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

I do not update these items nor have an id property for them on my main entity. Is it possible to know which entities are attached or not ?

Thanks in advance, Radu

Answer

Tri Q Tran picture Tri Q Tran · Sep 25, 2012

You can find the answer here.

public bool Exists<T>(T entity) where T : class
{
    return this.Set<T>().Local.Any(e => e == entity);
}

Place that code into your context or you can turn it into an extension like so.

public static bool Exists<TContext, TEntity>(this TContext context, TEntity entity)
    where TContext : DbContext
    where TEntity : class
{
    return context.Set<TEntity>().Local.Any(e => e == entity);
}