views:

320

answers:

2

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?

+2  A: 

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.

Craig Stuntz
Craig - I've seen that link. It says that "the provider must be able to return the server-generated identity value after a row is inserted. SQL Server can return the server-generated GUID type through the OUTPUT clause starting with SQL Server 2005."This seems to indicate to me that a stored procedure would be required. I was actually wanting to know if this is supported natively, and if so, why am I getting a "null" (all-zeros) identifier?
MissingLinq
No, [OUTPUT works with INSERT](http://msdn.microsoft.com/en-us/library/ms174335.aspx). Look at the generated INSERT and make sure it includes OUTPUT>
Craig Stuntz
+2  A: 

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

http://leedumond.com/blog/using-a-guid-as-an-entitykey-in-entity-framework-4/

MissingLinq
Does Microsoft have any plans to tweak the designer to support this?Opening up the .edmx file is troublesome at best.
KenB