views:

201

answers:

2

I have run into my first dissapointment with Entity Framework 4. It turns out that SQL CE, when used with EF4, does not support autogenerated primary keys. I get a System.Data.UpdateException from OnjectContext.SaveChanges() with this message:

Server-generated keys and server-generated values are not supported by SQL Server Compact.

So, now I have to manually generate keys for my entities. Assuming I want to use auto-incremented integer keys, what is the best way to go about generating and keeping track of the keys when using Entity Framework? Thanks for your help.

+1  A: 

At the bottom of the link in your question is a suggested solution. See SQL Compact, Identity Columns and Entity Framework perhaps you might want to implement an extension method like the one outlined.

DaveB
That's great--thanks!
David Veeneman
Good answer, but unfortunately, the code on the linked page only works for unfiltered entity sets, since the extension method returns the max id in the entity set. So, I ended up using a GUID as the entity key. I created a partial class for each entity with this constructor code: this.ID = Guid.NewGuid()
David Veeneman
A: 

i don't think David's ideal is a good ideal, however, i have no choise. Maybe CE will support autogenerated primary keys in next version.

gary
Actually, SQL Compact does support autogenerated keys--apparently, it's EF4 that doesn't support autogenerated keys from SQL Compact. The blog post linked in my original question explains the problem.
David Veeneman