Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
 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.

like image 827
Seth Avatar asked Aug 24 '11 21:08

Seth


1 Answers

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();
    }
}
like image 171
Kyle Trauberman Avatar answered Sep 25 '22 08:09

Kyle Trauberman