Home » Ado.Net » Entity Framework » Entity Framework 4.3: An object with the same key already exists in the ObjectStateManager

Entity Framework 4.3: An object with the same key already exists in the ObjectStateManager

This situation occur if you have already the object inside the DbContext and you try to Attach your instance. Most of the time you can manage it but just remove the Attach method but in some case that you might not know if the instance is inside the DbContext you may would like to check it before attaching.

This can be done with the help of DbSet and its Local property which is a collection of Locally attached entity.

if (!Database.Set<MyObject>().Local.Any(e => e.ID == myObject.ID))
    Database.MyObjects.Attach(myObject);
else
    myObject = Database.Set<MyObject>().Local.Single(e => e.ID ==  myObject.ID);

The first line verify if the Local repositor contains or not your object. This line use the primary has identifier (ID). If it doesn’t contain anything, the object is attached. Otherwise, your object will takes the reference of the one of the Local repository. This way, it won’t create a new instance of your object. Without the fourth line, you could end up with a new entry into the database even if the primary key is the same as an existing one (Entity Framework will do an Insert and the ID will auto-increment).

I am still curious to know why in some simple project, I can simply attach and never having the possibility to have twice the same object in the Local property.

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

5 Responses so far.

  1. Sunny says:

    Hello,

    Thanks for your sharing. And I want to know if you mind giving me your Email address.

  2. Patrick says:

    Hi,

    I’m trying to use your code in my repository, but it does not know any “ID”:

    public void Attach(T entity)
    {
    if (!_dbSet.Local.Any(e => e.ID == entity.ID))
    _dbSet.Attach(entity);
    }

    Both e.ID and entity.ID gets underlined because he don’t know where is it.

    Regards.

    • Your entity need to have an ID property. This is why T must inherit of your “BaseEntity” class which will have the primary key property defined here for all your entity. You must also define T to be class of your Base Entity.

  3. joe says:

    Have you found why in some simple project, we can simply attach and never get “An object with the same key already exists in the ObjectStateManager” error? I’m having the same problem too.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.