我们如何在 Entity Framework 7 上配置约定?

How do we configure conventions on Entity Framework 7?

在 EF7 之前,我使用下面的代码片段来删除约定:

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 上获得相同的结果?

约定的 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