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
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.
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.
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.
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); }
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