Entity Framework GUID Primary Key Error

Scenario:

Let's consider a scenario below:

We have a table with a GUID Primary Key with the below design:

Column Name Data Type
CategoryID uniqueidentifier
Category_Name nvarchar(50)
Category_Desc nvarchar(100)
   

Issue:

Now, we want to save data into with and the Primary Key is generated via C# code using the line : Guid CategoryID = Guid.NewGuid(); Although, while executing the line .SaveChanges(), an error is encountered saying that the Primary Key: CategoryID is null and it shows to have the default value 00000000-0000-0000-0000-000000000000.

This issue happens because the GUID field is Primary Key and Identity Key as well and so the SQL assumes that the GUID will be created on the DB end and so the value provided by the C# code is dropped and does not go the DB and as there is no default value mentioned at the DB end, so the error is prompted stating that the GuiD is Null.

Resolution:

Now, we have two ways to solve this error:
  1. Either we can define it on the DB end to get a default value of the GUID Field. Then it would be the task of the DB to create a new Guid everytime an insert statement is called.

  2. Another way is to open the emdx file is by right clicking it and selecting the option : "Open With", then from the options select "XML (text) Editor". Then scroll to the definition of the concerned table and notice a property of the CategoryID field as StoreGeneratedPattern="Identity". Replace the "Identity" with "None".
Save it and the issue would be resolved.
I hope this helped many Entity Framework users out there.

Feel free to comment with your doubts.
Thanks
Vipul