Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF returns 0000-0000-0000-xxx as Guid when I try save a new record or update existing record?

I am using EF4 in my C# project. The problem I'm faced with is that, when I try to save a record, I get a Primary Key Violation and the PK value is "0000-0000-0000-xxx". From my guess, EF does not recognize the IsIdentity flag and generate a guid value. In my SQL Server database for my table, I specify a PK(uniqueidentifier>guid) and also set it as the IdentityColumn, thus I would expect this to travel through to my project as such since the guid is generated in SQL Server. Is there a way to overcome this bug?

like image 954
Donald N. Mafa Avatar asked Nov 05 '25 09:11

Donald N. Mafa


1 Answers

You must specify your Guid ID as an Identity in your EF model. In EF 4.1:

[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }

(Guid Ids are not identities by default, in contrast to int Ids.) If you create the database with this model EF will create a column with a default value of newid().

In EF 4.0 you can go to the model designer, mark your Id property in the designer, open the properties window and then set StoreGeneratedPattern to Identity.

like image 66
Slauma Avatar answered Nov 07 '25 05:11

Slauma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!