EF 4.1 CodeFirst with Guid (not generated by DB / Store) as PK

I would like to create a model with a "generated client" GUID as the primary key. I want Guid to be automatically generated, but NOT on the database, so I know the identifier before I save it, which is important for my domain model.

How to setup:

class MyEntity { public Guid ID { get; set; } } 

So what can I do ...

  var newEntity = new MyEntity(); transmitIDBeforePersisting(newEntity.ID); context.MyEntities.Add(newEntity); context.SaveChanges() 

How to configure MyEntity.ID so that it is automatically generated when new is called, but still works correctly as a Primary key, with nav properties, etc.?

This is similar to using Guid as PK with the first EF4 code , but NOT generated by the repository / DB.

+7
source share
1 answer

Set the ID property value in your constructor and use the [DatabaseGenerated(DatabaseGeneratedOption.None)] attribute in the ID property:

 public class MyEntity { [DatabaseGenerated(DatabaseGeneratedOption.None)] public Guid ID { get; set; } public MyEntity() { ID = Guid.NewGuid(); } } 
+9
source

All Articles