Saturday, December 31, 2011

GUIDs, Primary Keys, and The Entity Framework

I spent the evening learning about ASP.Net MVC 3 and thought I would share this bit of information with you.  By default the entity framework uses integers for entity identifiers. After years of battling with scaleability issues, company mergers, and database consolidation projects I have come to prefer using GUIDs over integers or longs for tuple identity. The first thing I tried to do was change the POCO's datatype to GUID. However, the default value was being set to 16 zeros! 

After a bit of STFW, I found this article that came up with a work around generating the Guid inside of the model. Then I found a MS support ticket where you could set StoreGeneratedPattern in some ridiculous xml configuration file. Thankfully I learned that EF also supports the use of attributes via System.ComponentModel.DataAnnotations:

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

No comments: