EF 4.1 CodeFirst with Guid (not generated by DB/Store) as PK
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();
transmitIDBefor开发者_C百科ePersisting(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();
}
}
精彩评论