Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq-to-sql

I have a linq2sql setup where objects are sent from client side (flex via flourinefx) and attach them to a new datacontext a seen below:

I also have a "global" datacontext that is used throughout the session.

    public static void Update(Enquiry enquiry)
    {
        OffertaDataContext db = new OffertaDataContext();


        db.Enquiries.Attach(enquiry);
        db.Refresh(RefreshMode.KeepCurrentValues, enquiry);

        db.SubmitChanges();
    }

This approach usually works fine, but after a while I get the error "Cannot add an entity with a key that is already in use".

like image 720
Niels Bosma Avatar asked Jan 07 '09 15:01

Niels Bosma


4 Answers

I was getting this error and it was because I had forgotten to set the Primary Key field in the database to "Identity Specification" (auto-increment). When I changed this I was good. Doh!

like image 103
vealer Avatar answered Oct 24 '22 09:10

vealer


I think this error happens if you Attach an entity to a DataContext that was already loaded.

The code that causes the error is exactly like you show here? After creating the new OffertaDataContext do you query anything before the Attach?

like image 37
bruno conde Avatar answered Oct 24 '22 09:10

bruno conde


This might not be your issue (I can't tell), but it was mine and as people google this it might help someone else. If you aren't using the built-in Linq-to-SQL designer or SQLMetal stuff to generate your Linq-to-SQL classes, or if you forgot to make your ID column an IDENTITY, you may be missing a property on your column attribute called "IsDbGenerated". Be sure your column attribute looks something like this:

<Column(Name:="ID", DbType:="Int NOT NULL IDENTITY", CanBeNull:=False, IsPrimaryKey:=True, IsDbGenerated:=True)>
like image 5
mattmc3 Avatar answered Oct 24 '22 07:10

mattmc3


In case you inserting several entities at once, may you are just trying to insert a duplicate entity into current datacontext. I know this is too simple, but it just happened to myself.

like image 5
Julio Nobre Avatar answered Oct 24 '22 08:10

Julio Nobre