using Guid as PK with EF4 Code First

Omu picture Omu · Mar 11, 2011 · Viewed 11k times · Source

I have this class and table:

public class Foo
{
public Guid Id {get;set;}
public string Name {get;set;}   
}

create table Foo
(
id uniqueidentifier primary KEY DEFAULT (newsequentialid()),
name nvarchar(255)
)

the problem is that when i try to save new foo the first one goes with the 0000-000-00 ... id and the second also, so I get constraint exception

anybody knows a fix ?

Answer

Devart picture Devart · Mar 11, 2011

Have you set Identity StoreGeneratedPattern?
You can do it in the OnModelCreating method:

modelBuilder.Entity<Foo>().Property(o => o.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

or using the DataAnnotation attributes:

public class Foo {
  [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
  public Guid Id {get;set;}
  public string Name {get;set;}
}