在EF7之前,我使用下面的snipet删除约定:
protected override void OnModelCreating(DbModelBuilder builder)
{
builder.Conventions.Remove<NavigationPropertyNameForeignKeyDiscoveryConvention>();
builder.Conventions.Remove<PrimaryKeyNameForeignKeyDiscoveryConvention>();
builder.Conventions.Remove<PluralizingTableNameConvention>();
builder.Conventions.Remove<PrimaryKeyNameForeignKeyDiscoveryConvention>();
builder.Conventions.Remove<TypeNameForeignKeyDiscoveryConvention>();
}
我们如何在Entity Framework 7上实现相同的结果?
答案 0 :(得分:5)
约定的API目前还不稳定。请参阅https://github.com/aspnet/EntityFramework/issues/2589。
可以这样做,但它需要使用依赖注入来覆盖在上下文中调用OnModelCreating
的内部工作方式。 DbContext
使用依赖注入来查找提供模型构建器(和约定)的ModelSource
实例。
要覆盖模型源,请将您自己的实现添加到依赖注入:
var serviceCollection = new ServiceCollection();
serviceCollection
.AddEntityFramework()
.AddSqlServer();
serviceCollection.AddSingleton<SqlServerModelSource, MyModelSource>();
var serviceProvider = serviceCollection.BuildServiceProvider();
using(var context = new MyContext(serviceProvider))
{
// ...
}
MyModelSource
的实施应覆盖ModelSource.CreateConventionSet()
。请参阅original source here