Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Code First versus Guid

In my simple class I'm using data annotations to map properties to columns as such:

[Table("Member")]
public class Member
{
    [Key]
    public Guid MemberId { get; set; }

    // More properties go here
}

I can already write new members to my table but MemberId always defaults to a new Guid (0000-000-00...) instead of a beautiful server generated Guid.

I've seen scenarios where people change some setting called StoreGeneratedPattern in an EDMX file. But since I'm using Code First obviously I don't have this EDMX file...

So how would I go about solving this?

Any help is very much appreciated.

UPDATE!!

Ok, just found the answer myself. You can use an annotation.

[Table("Member")]
public class Member
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid MemberId { get; set; }

    // More properties go here
}
like image 725
Aetherix Avatar asked Apr 20 '12 13:04

Aetherix


2 Answers

Use an annotation:

[Table("Member")]
public class Member
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid MemberId { get; set; }

    // More properties go here
}
like image 161
Aetherix Avatar answered Oct 05 '22 00:10

Aetherix


I have been initializing my Guids in the class constructor since you don't need / can't use the auto-increment functionality that you use with int type keys.

So, I would change to...

[Table("Member")]
public class Member
{
    [Key]
    public Guid MemberId (get; set;}

    public Member
    {
      MemberId = Guid.NewGuid();
    }
}
like image 43
vansimke Avatar answered Oct 04 '22 23:10

vansimke