home » 2012 » 12 » The "Cannot add an entity with a key that is already in use." error

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

Posted:
2012-12-18
Tags:
c# debugging

If you are getting the above Linq2sql error, here is the first thing you should do. It will not solve the problem for you, but it will greatly help you when tracking down the root cause:

try
{
    db.SubmitChanges();
}
catch (DuplicateKeyException dke)
{
    Console.WriteLine(
        "DuplicateKeyException caused by {0}!",
        dke.Object
    );
    throw;
}

Yeah I know, it's not much. :) But this way you know the entity instance that is caused the problem which will make your code much (much) easier to debug.