Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework - SaveChanges with GUID as EntityKey

I have a SQL Server 2008 database table that uses uniqueidentifier as a primary key. On inserts, the key is generated on the database side using the newid() function.

This works fine with ADO.NET. But when I set up this table as an entity in an Entity Framework 4 model, there's a problem. I am able to query the entity just fine, but when creating a new entity and invoking SaveChanges() on the context, the generated uniqueidentifier on the database is all zeros.

I understand there was an issue with EF v1 where this scenario did not work, requiring creating the GUID on the client prior to calling SaveChanges. However, I had read in many places that they were planning to fix this in EF 4.

My question -- is this scenario (DB-side generation of uniqueidentifier) still not supported in EF4? Are we still stuck with generating the GUID on the client?

like image 699
MissingLinq Avatar asked May 13 '10 13:05

MissingLinq


2 Answers

Thanks guys, finally got it figured out. Blogged the answer here:

https://web.archive.org/web/20100518175148/http://leedumond.com/blog/using-a-guid-as-an-entitykey-in-entity-framework-4/

like image 159
MissingLinq Avatar answered Nov 02 '22 00:11

MissingLinq


Yes, this changed in EF 4. You can now use a server generated GUID. @MusiGenesis, server-generated GUIDs have some advantages; they can be sequential, e.g.

like image 4
Craig Stuntz Avatar answered Nov 02 '22 01:11

Craig Stuntz