【问题标题】:How do we configure conventions on Entity Framework 7?我们如何在 Entity Framework 7 上配置约定?
【发布时间】:2015-12-08 17:35:00
【问题描述】:

在 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 上实现相同的结果?

【问题讨论】:

    标签: entity-framework ef-code-first entity-framework-core


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-31
      • 2015-11-07
      • 2016-03-31
      • 2017-03-23
      • 1970-01-01
      • 1970-01-01
      • 2016-08-04
      • 1970-01-01
      相关资源
      最近更新 更多