Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using database generated GUID and datetime with EF4

I have a simple table with an ID (a uniqueidentifier), a datetime, and a value.

I'd like to use getdate() on the database for the record insertion time and newid() for the id. How do I configure entity framework to do this? When I try to assign the id on the DB I get:

Violation of PRIMARY KEY constraint 'PK_Random'. Cannot insert duplicate key in object 'dbo.Random'. The duplicate key value is (00000000-0000-0000-0000-000000000000).
like image 864
DenaliHardtail Avatar asked Feb 26 '11 03:02

DenaliHardtail


2 Answers

Just to add to this since @lunateck answer helped me. The other way (if you are using Database First) is to:

  1. Open your edmx file.
  2. Right click -> Model Browser
  3. Right click the Guid column -> Properties -> change the StoreGeneratedPattern to Identity.
like image 138
klamoree Avatar answered Nov 20 '22 00:11

klamoree


if you are using code first. Please add the following to your guid.

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid guId { get; set; }

This will enable sql server side guid generation. Hope it helps.

like image 25
lunateck Avatar answered Nov 20 '22 01:11

lunateck