问题
I am using EF4 in my C# project. The problem I'm faced with is that, when I try to save a record, I get a Primary Key Violation and the PK value is "0000-0000-0000-xxx". From my guess, EF does not recognize the IsIdentity flag and generate a guid value. In my SQL Server database for my table, I specify a PK(uniqueidentifier>guid) and also set it as the IdentityColumn, thus I would expect this to travel through to my project as such since the guid is generated in SQL Server. Is there a way to overcome this bug?
回答1:
You must specify your Guid
ID as an Identity in your EF model. In EF 4.1:
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
(Guid
Ids are not identities by default, in contrast to int
Ids.)
If you create the 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 designer, open the properties window and then set StoreGeneratedPattern
to Identity
.
回答2:
Instead of this:
public System.Guid ID { get; set; }
Try this:
private System.Guid _id;
public System.Guid ID
{
get
{
if (_id == null || _id == Guid.Empty)
_id = Guid.NewGuid();
return _id;
}
set
{
_id = value;
}
}
来源:https://stackoverflow.com/questions/7174065/ef-returns-0000-0000-0000-xxx-as-guid-when-i-try-save-a-new-record-or-update-exi