using Guid as PK with EF4 Code First
Asked Answered
O

2

39

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 ?

Oratorical answered 11/3, 2011 at 8:41 Comment(0)
C
71

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;}
}
Chastitychasuble answered 11/3, 2011 at 8:53 Comment(0)
K
17

Just building on Devart's Solution, I had this issue and using the

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]

data annotation didn't work. The reason for this was i was using (as suggested in one of the code first tutorials) a SqlServerCompact database which doesn't support the Guid as identity. Just thought I'd post here in case anyone else had this issue. If you change the connection string so it is creating a SqlServer mdf instead of a Compact database it works perfectly.

Kalevala answered 20/2, 2012 at 16:10 Comment(3)
What version of the Compact Edition and EF were you using? It seems okay with CE 4.0 and EF 6. Was this resolved in subsequent versions of CE?Whipple
@Whipple it probably has been resolved then, my post was a couple of years ago :)Kalevala
@Kalevala I face this problem now in VS2013 Update 2 with EF 6.1.0.Hoi

© 2022 - 2024 — McMap. All rights reserved.