For my primary key and identity in our Clients table I use uniqueidentifier
column with a default value set to newsequentialid(). Inserting new rows through the management tool creates the values for the ID fine.
Inserting from .NET 4 code via EF results into zero GUIDs (00000-0000....) being inserted. I create the entity with new, set some values and perform EF AddToClients
(for instance). If debugged, value for the id property shows zero GUID. I do not explicitly set the id via the Guid.NewGuid()
in my code because I want to leave it off to the newsequentialid()
in SQL Server. The problem is, it doesn't work. The first time the code is executed row gets inserted with zero GUID. The next time it obviously fails and results in primary key violation exception.
How can I get this to work without having to set the GUID in my client code?
The globally unique identifier (GUID) data type in SQL Server is represented by the uniqueidentifier data type, which stores a 16-byte binary value. A GUID is a binary number, and its main use is as an identifier that must be unique in a network that has many computers at many sites.
GUIDs can be considered as global primary keys. Local primary keys are used to uniquely identify records within a table. On the other hand, GUIDs can be used to uniquely identify records across tables, databases, and servers.
Yes, there are a number of ways you can auto-generate key values for your tables. The most common ways are via the use of the IDENTITY column property or by specifying a uniqueidentifier (GUID) data type along with defaulting with either the NEWID() or NEWSEQUENTIALID() function.
The GUID data type is a 16 byte binary data type. This data type is used for the global identification of objects, programs, records, and so on. The important property of a GUID is that each value is globally unique. The value is generated by an algorithm, developed by Microsoft, which assures this uniqueness.
You need to change the StoreGeneratedPattern
value for the property in the EF designer. Set it to Identity
. This will cause EF to avoid setting the value on an insert, then capture it after the insert is complete.
Note that if you're using EF 4, you may have trouble with this using the designer only (see this link). You may have to edit the .edmx manually and set the StoreGeneratedPattern
in the storage model itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With