DatabaseGeneratedOption.None的约定 [英] Convention for DatabaseGeneratedOption.None
问题描述
我想为所有实体手动插入ID。
是否可以创建某种约定,或者我必须为每个实体设置HasDatabaseGeneratedOption(DatabaseGeneratedOption.None)(或添加DatabaseGenerated属性)?
I would like to manually insert id for all my entities. Is it possible to create some kind of convention or I have to set HasDatabaseGeneratedOption(DatabaseGeneratedOption.None) (or add DatabaseGenerated attribute) for every entity ?
编辑
有一个更简单的方法,然后使用接受的答案:
There is a simpler way to do this then using accepted answer:
modelBuilder.Conventions.Remove<StoreGeneratedIdentityKeyConvention>();
推荐答案
可以在EntityFramework 6中创建自定义约定,如下所示:
It's possible to create custom conventions in EntityFramework 6 as follows:
创建公约类
public class ManualIdentityConvention : Convention
{
public ManualIdentityConvention()
{
this.Properties<int>()
.Where(p => p.Name.EndsWith("Id"))
.Configure(p => p.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None));
}
}
将约定添加到DbContext
public class Context : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Add(new ManualIdentityConvention());
}
}
EntityFramework 5
至于EntityFramework 5,我认为可以实现类似的功能,但不能通过常规类实现:
As for EntityFramework 5, I believe something similar can be achieved, but not via a convention class:
public class Context : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Properties<int>()
.Where(x => x.Name.EndsWith("Id"))
.Configure(x => x.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None));
}
}
在任何一种情况下,这两种方法都不是特别外科手术,但是可以想像的是,可以通过在where子句中更具体一些来加强约定。
In either case, neither approach is particularly surgical, but one could conceivably tighten up the convention by being more specific in one's where clause.
这有帮助吗?
这篇关于DatabaseGeneratedOption.None的约定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!