0

I am getting the "An object with the same key already exists" on an update attempt while trying to attach an entity.Lazy loading is turned on. I googled, and found no real solution to this problem. My best solution would be to replace the entry in the object state manager, but I can not find anywhere how to replace it. Is it possible at all?

the problems occurs when I create an instance of object A (has a collection of Object B) in one context, and the B objects in another context. When I try to attach both of them it breaks. Is there a way to tell EF when to replace the entry that it is tracking. Could it maybe be possible that it would allow the replacement when I would set the duplicated entitykey entries objectstate to modified.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user853710
  • 1,715
  • 1
  • 13
  • 27

1 Answers1

3

There are two parts to your problem.

1. Detecting if an entity is already being tracked by the context.

If you have two references to the same instance of an entity it is easy to see if it is being tracked.

Boolean isTracked = context.MyEntities.Local.Contains(myEntity);

If you instead have two instances of an entity that is conceptually the same because they have the same key then things can be more difficult.

Boolean isTracked = context.MyEntities.Local.Any(x=>x.Id == myEntity.Id);

Or alternatively using an EqualityComparer<T>:

public class MyEntityEqualityComparer : EqualityComparer<MyEntity>
{
   public override bool Equals(MyEntity x, MyEntity y)
   {
      return x.Id == y.Id;
   }

   public override int GetHashCode(MyEntity obj)
   {
      return obj.Id;
   }
}

context.MyEntities.Local.Contains(myEntity, new MyEntityEqualityComparer());

2. Switching out the entity being tracked.

This can be achieved like so:

context.Entry<MyEntity>(entityToReplace).State = EntityState.Detached;
context.MyEntities.Attach(entityToAdd);

However, before you do all this you should look at your application design. Having to juggle entities between contexts can be a sign that you are not grouping tasks into appropriate units of work where you could operate on a single context.

  • Seems legit. I did one project with a single context object and never again. ;) Some things here, I will have to do in a different way. On the one hand that for instance "Entry" came since EF 4.1 (I use 4.0), on the other hand, I created generic classes that I use for ataching. Anyway I think this might work. THNX – user853710 Jul 22 '13 at 11:23