Using database generated GUID and datetime with EF

2020-06-03 03:40发布

问题:

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).

回答1:

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.



回答2:

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.