Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using Guid as PK with EF4 Code First

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 ?

like image 679
Omu Avatar asked Mar 11 '11 08:03

Omu


People also ask

Can a GUID be a primary key?

GUIDs can be considered as global primary keys. Local primary keys are used to uniquely identify records within a table. On the other hand, GUIDs can be used to uniquely identify records across tables, databases, and servers.

How to define primary key in c#?

The primary key for a table is set by specifying an array of DataColumn objects from the table. The following example illustrates creating a primary key based on two columns: // set the primary key based on two columns in the DataTable DataTable dt = new DataTable("MyTable"); dt. Columns.

What is Databasegenerated DatabaseGeneratedOption identity?

DatabaseGeneratedOption.IdentityThis specifies that the value of the property will be generated by the database on the INSERT statement. This Identity property cannot be updated. Please note that the way the value of the Identity property will be generated by the database depends on the database provider.


2 Answers

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;} } 
like image 149
Devart Avatar answered Sep 23 '22 00:09

Devart


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.

like image 23
Manatherin Avatar answered Sep 23 '22 00:09

Manatherin