EF 4.1 CodeFirst with Guid(不是由DB / Store生成)作为PK [英] EF 4.1 CodeFirst with Guid (not generated by DB/Store) as PK
问题描述
我想用客户端生成GUID创建一个模型作为主键。我想要Guid自动生成,但不是在DB上,所以我知道ID之前我坚持,对我的域模型很重要。
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.
我如何设置:
class MyEntity {
public Guid ID { get; set; }
}
所以我可以做...
var newEntity = new MyEntity();
transmitIDBeforePersisting(newEntity.ID);
context.MyEntities.Add(newEntity);
context.SaveChanges()
如何设置MyEntity.ID,当我打电话给新的,但仍然正常工作作为主键,导航属性等?
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?
这与使用Guid作为PK与EF4代码第一,但不是由商店/ DB生成。
This is similar to using Guid as PK with EF4 Code First, but NOT generated by the Store/DB.
推荐答案
在构造函数中设置 ID
属性的值,并使用 [DatabaseGenerated(DatabaseGeneratedOption.None)]
属性 ID
属性:
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();
}
}
这篇关于EF 4.1 CodeFirst with Guid(不是由DB / Store生成)作为PK的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!