Does EF return 0000-0000-0000-xxx as Guid when I try to save a new record or update an existing record?

I am using EF4 in my C # project. The problem I am facing is that when I try to save the record, I get a primary key violation and the PK value is "0000-0000-0000-xxx". By my assumptions, EF does not recognize the IsIdentity flag and generates a guid value. In my SQL Server database for my table, I specify PK (uniqueidentifier> guid) and also set it as IdentityColumn, so I expect this to move to my project as such, since guid is generated in SQL Server. Is there any way to overcome this error?

+1
source share
2 answers

You must specify your Guid ID as an identifier in your EF model. In EF 4.1:

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

( Guid identifiers are not identifiers by default, unlike int Ids.) If you create a database with this model, EF will create a column with a default value of newid() .

In EF 4.0, you can go to the model designer, mark your Id property in the constructor, open the properties window, and then set StoreGeneratedPattern to Identity .

+8
source

Instead of this:

 public System.Guid ID { get; set; } 

Try the following:

 private System.Guid _id; public System.Guid ID { get { if (_id == null || _id == Guid.Empty) _id = Guid.NewGuid(); return _id; } set { _id = value; } } 
+2
source

All Articles