Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EntityFramework Code First - Check if Entity is attached

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

like image 710
Radu Negrila Avatar asked Apr 05 '12 11:04

Radu Negrila


People also ask

Is Entity Framework connected or disconnected?

There are 2 ways (connected and disconnected) when persisting an entity with the Entity Framework. Both ways have their own importance. In the case of a connected scenario the changes are tracked by the context but in the case of a disconnected scenario we need to inform the context about the state of the entity.

What is include in Entity Framework?

Entity Framework Classic Include The Include method lets you add related entities to the query result. In EF Classic, the Include method no longer returns an IQueryable but instead an IncludeDbQuery that allows you to chain multiple related objects to the query result by using the AlsoInclude and ThenInclude methods.

What is EntityState in Entity Framework?

EF API maintains the state of each entity during its lifetime. Each entity has a state based on the operation performed on it via the context class. The entity state represented by an enum System.


1 Answers

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); } 
like image 171
Tri Q Tran Avatar answered Nov 12 '22 20:11

Tri Q Tran