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

痴心易碎 提交于 2019-12-12 10:38:58

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/7182805/ef-4-1-codefirst-with-guid-not-generated-by-db-store-as-pk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!