I am creating and filling LINQ to SQL objects programatically and then adding them to a sql server database with a uniqueidentifier column for a PK. LINQ is automatically assigning a PK of all 0s. This creates errors upon insert because the PK is a duplicate.
Dim myNewRecord as IceCreamTrackerTable
myNewRecord.name=Bob
myNewRecord.favoriteIceCream=Vanilla
'myNewRecord.PK=00000000-0000-0000-0000-000000000000 (by default)'
myDataContext.IceCreamTrackerTables.insertOnSubmit(myNewRecord)
''second record added throws an error because it also has PK 00000 etc.
- I know that I can assign the PK using myNewRecord.pk=Guid.newGuid()
Guid is all 0's (zeros)? - But what I really want is for SQL server to be assigning the GUIDs because I’m assuming that it has some method to make sure that it is not re-assigning the same guid
Is there any way to tell LINQ that I don’t want to fill the GUID myself but leave it up to SQL server?
Guid’s are value types, thus they cannot be null. That means when a Guid is created, it has to assign a default value (which is all 0’s). SQL Server does not automatically generate GUID’s for primary keys like it does for Identity columns. You can set the default value to NEWID(), but by default EF will ignore that and try to insert a value. You can override this by doing something like described here
http://softmindit.blogspot.com/p/using-guid-as-entitykey-in-entity.html
EDIT: I just realized you’re using Linq to sql not Linq to entities. However, i’m sure there’s something similar in L2S to deal with this.
Edit2: There is a similar thing in linq to sql, as shown in the screenshot. Changing this property fixes the problem