Entity Framework model – uniqueidentifier primary keys

The Entity Framework has had a number of additions and fixes created over the years, and one I particularly like is the way to specify how to handle a GUID or rather a primary key in SQL Server of type uniqueidentifier. Previously you had to manually open the .edmx file in say Notepad and add the StoreGeneratedPattern attribute to your PK column and set the value to Identity. That in itself wasn’t too hard, but when you made changes to the model and saved it, those manual changes were overwritten. Now, the StoreGeneratedPattern attribute is part of the Visual Studio UI, or rather the Properties window in Visual Studio, making it easy to handle.

Let me point out, that the above scenario is really only applicable, if you do not have SQL Server handle the addition of a new row, by creating a new primary key value, by say using the newid or newsequentialid functions. If you have SQL Server handle the addition of a new row, you can set the StoreGeneratedPattern attribute to Identity, and in your partial entity class (say Country), you decorate the id column with the AllowEmptyStrings attribute and a value of false, like this:

public partial class Country
     internal class Country_Metadata
        [Required(AllowEmptyStrings = false)]
        public object Id { set; get; }
If your code adds the primary key, before you attempt to save it to the database, there’s little reason to set the StoreGeneratedPattern attribute.