问题
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 ?
EDIT
There is a simpler way to do this then using accepted answer:
modelBuilder.Conventions.Remove<StoreGeneratedIdentityKeyConvention>();
回答1:
It's possible to create custom conventions in EntityFramework 6 as follows:
Create a convention class
public class ManualIdentityConvention : Convention
{
public ManualIdentityConvention()
{
this.Properties<int>()
.Where(p => p.Name.EndsWith("Id"))
.Configure(p => p.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None));
}
}
Add the convention to your DbContext
public class Context : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Add(new ManualIdentityConvention());
}
}
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));
}
}
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.
Does this help?
来源:https://stackoverflow.com/questions/24805637/convention-for-databasegeneratedoption-none