EF returns 0000-0000-0000-xxx as Guid when I try save a new record or update existing record?
Asked Answered
M

2

4

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?

Manes answered 24/8, 2011 at 10:37 Comment(0)
S
12

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.

Sweep answered 24/8, 2011 at 18:55 Comment(1)
Thanks for your information. setting the storegeneratedpattern fix it.Stand
R
3

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;
    }
}
Reminiscent answered 24/8, 2011 at 16:51 Comment(1)
_id can never be null because it is a value type. The only value type that can be compared against null is Nullable<T>.Nutty

© 2022 - 2024 — McMap. All rights reserved.