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

clinq-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".

Best Answer

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!