7

I'd like to create a model with a 'client generated' GUID as the primary key. I want the Guid to be auto-generated, but NOT on the DB, so I know the ID before I persist it, important for my domain model.

How do I setup:

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

So I can do...

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

How can I setup MyEntity.ID so it is auto-generated when I call new, but still works properly as a Primary Key, with nav properties, etc?

This is similar to using Guid as PK with EF4 Code First, but NOT generated by the Store/DB.

Community
  • 1
  • 1
Seth
  • 2,712
  • 3
  • 25
  • 41
  • Perhaps this answer from just 5 hours ago is helpful for you: http://stackoverflow.com/questions/7174065/ef-returns-0000-0000-0000-xxx-as-guid-when-i-try-save-a-new-record-or-update-exis/7179259#7179259 – Slauma Aug 24 '11 at 22:12

1 Answers1

9

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

public class MyEntity 
{        
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public Guid ID { get; set; }

    public MyEntity()
    {
        ID = Guid.NewGuid();
    }
}
Kyle Trauberman
  • 25,414
  • 13
  • 85
  • 121