LOGIC Library

This site is the Logic involvement in sharing expertise and skills acquired in daily work. The goal is to create a solid knowledge base and share best practices in software development and systems management.

More info about us can be found on logicsistemi.it.

An object with the same key already exists in the ObjectStateManager

When working with Entity Framework, we could encounter the following error: An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key. In this article, we understand what it exactly means and how to solve it.

The problem arises from the way the ObjectContext works. Under ordinary conditions, ObjectContext stores in its cache an instance (and only one) of the ObjectStateEntry class for every entity. That means that we can't have more than one entity (i.e. record) with the same key in the cache.

Even if this seems to be obvious, in some circumstances this is not the behaviour we want. We can solve the problem in different ways. Here we provide a trick.

Let's start by reproducing the problem (I'm sorry if the following example is so trivial, but the only goal is to reproduce the error):

TestMVCEntities db = new TestMVCEntities();
News testNews = new News(); testNews.NewsID = 1; db.News.Attach(testNews);
News testNews2 = new News(); testNews2.NewsID = 1; db.News.Attach(testNews2);

When we execute this code, we have the error An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key. That's because we Attach to the context the same Entity (notice the key).

An easy way to prevent from that problem is to use two different contexts. Look at this code:

TestMVCEntities db = new TestMVCEntities();
TestMVCEntities db2 = new TestMVCEntities();
News testNews = new News(); testNews.NewsID = 1; db.News.Attach(testNews);
News testNews2 = new News(); testNews2.NewsID = 1; db2.News.Attach(testNews2);

In this last snippet of code, we've used two different contexts that have two different caches. That's why we don't have any error.

Comments   

 
#1 Mastigado 2013-10-29 19:01
Thank you very much!
Quote