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.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With