Навигация

Итоги года

Другие ссылки


Реклама

Счётчики


Cannot add an entity with a key that is already in use

04.09.2008 Четверг 13:14

Related to: .Net 3.5, C#, LINQ, LINQ-to-SQL

Got the following error:

Cannot add an entity with a key that is already in use.

at the following line:

Context.SubmitChanges();

This error usually happens when the database and the Context object are out-of-sync. This may happen when:

a. You change database outside of the Context object. For example by directly executing command using SqlCommand class.

b. When you use more than one Context object to update database.

To solve this issue, either always use the same Context object to update database, or refresh all Context objects you use after a change in database made through one of them or oustide any Context object. To achieve this just re-create the object:

MyContext context;
...
context.Dispose();
context = new MyContext();


However, this will most likely discard all unsubmitted changes made through the Context object updated in such a manner. So you have to accomodate for the changes before refreshing your context objects.