Linq to SQL inserting a value for a primary key?

Hi Guys,

I’ve got a linq to sql query all set up and for some reason it’s trying to insert a value for the primary keys of one of the tables, even though I’m not specifying it at all.

Below is my code:


        Dim myGoogleContext As New GoogleMapsExperimentDataContext
        Dim usr As New user With
            {.username = "new name"
                }
        ' Add the new object to the users collection.
        myGoogleContext.users.InsertOnSubmit(usr)

        Dim addr As New address With
            {.test = "final address",
             .userId = usr.userId
                }

        ' Add the new object to the address collection.
        myGoogleContext.addresses.InsertOnSubmit(addr)
        myGoogleContext.SubmitChanges()

The addresses table only has 3 columns, (addressId,userId(which is a foreign key), and test.
As you can see, I haven’t mentioned the addressId, but the code is trying to insert it (With a value of zero I believe).

This results in me getting the following error:
“Cannot insert explicit value for identity column in table ‘addresses’ when IDENTITY_INSERT is set to OFF.”

Can anyone please tell me why it’s trying to insert the addressId without me telling it to?
It’s an identity column and a primary key, so I’m not touching it directly.

Any advice would be appreciated.

I think I may have figured out the problem.
I deleted my linq to sql class file , refreshed the tables in the database explorer, dragged them over again into the linq to sql class and all seems to be well now.

I also made sure that the primary keys of the 2 tables were set to identities.

But why was this a problem in the first place?

Surely if I wasn’t specifically mentioning the addressId in the insert statement it shouldn’t have tried to insert it?

I’d still like an explanation to help me avoid this in future if anyone has any insight.