Convention for DatabaseGeneratedOption.None

风格不统一 提交于 2020-01-05 12:30:33

问题


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

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