构造函数中带有DbOptions的实体框架核心DbContext继承问题

时间:2019-02-11 09:28:46

标签: entity-framework .net-core entity-framework-core asp.net-core-2.1 entity-framework-core-2.1

在我们的项目中,我们有一个数据库,在该数据库中使用数据库优先方法。由于我们使用的功能不会被架设,因此我有了第二个DBContext,它继承了所生成的功能。这使我避免了每次发生数据库更改时都手动操作生成的数据库上下文。

因此StartUp中的类定义和用法如下:

  // the db context generated by scaffolding the database
  public partial class ApplicationDatabaseContextGenerated : DbContext
  {
    public ApplicationDatabaseContextGenerated() {}
    public ApplicationDatabaseContextGenerated(DbContextOptions<ApplicationDatabaseContextGenerated> options) : base(options) {}

    // the db sets scaffolded
  }

  // the db context used by the app with the extended functionality
  public class ApplicationDatabaseContext : ApplicationDatabaseContextGenerated
  {

    public ILogger<ApplicationDatabaseContext> Logger { get; protected set; }

    public ApplicationDatabaseContext() : base() {}

    public ApplicationDatabaseContext(DbContextOptions<ApplicationDatabaseContext> options, ILogger<ApplicationDatabaseContext> logger) : base(options)
    {
      Logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    // the extended functionality like views and functions

  }

  // how I use it in startup
  public void ConfigureServices(IServiceCollection services)
  {
    // other things ...

    services.AddDbContext<ApplicationDatabaseContext>(options => options.UseNpgsql(Configuration.GetConnectionString("db1-connection")));

    // other things ...
  }

不幸的是,这导致编译错误突出显示ApplicationDatabaseContext构造函数的base(选项),说明:

Error CS1503 Argument 1: cannot convert from 'Microsoft.EntityFrameworkCore.DbContextOptions<... ApplicationDatabaseContext>' to 'Microsoft.EntityFrameworkCore.DbContextOptions<... ApplicationDatabaseContextGenerated>'

我想,聪明一点,ApplicationDatabaseContextGenerated基本上是数据库上下文,并将ApplicationDatabaseContextGenerated的构造函数更改为:

  public ApplicationDatabaseContextGenerated(DbContextOptions<DbContext> options) : base(options) {}

不,这是不允许的,并且导致:

Error CS1503 Argument 1: cannot convert from 'Microsoft.EntityFrameworkCore.DbContextOptions<... ApplicationDatabaseContext>' to 'Microsoft.EntityFrameworkCore.DbContextOptions<Microsoft.EntityFrameworkCore.DbContext>'

好,我们都将其作为DbContext

  // the db context generated by scaffolding the database
  public partial class ApplicationDatabaseContextGenerated : DbContext
  {
    public ApplicationDatabaseContextGenerated() {}
    public ApplicationDatabaseContextGenerated(DbContextOptions<DbContext> options) : base(options) {}

    // the db sets scaffolded
  }

  // the db context used by the app with the extended functionality
  public class ApplicationDatabaseContext : ApplicationDatabaseContextGenerated
  {

    public ILogger<ApplicationDatabaseContext> Logger { get; protected set; }

    public ApplicationDatabaseContext() : base() {}

    public ApplicationDatabaseContext(DbContextOptions<DbContext> options, ILogger<ApplicationDatabaseContext> logger) : base(options)
    {
      Logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    // the extended functionality like views and functions

  }

漂亮,可以编译。让我们开始吧,我们得到:

  System.InvalidOperationException: No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.
    at Microsoft.EntityFrameworkCore.Internal.DbContextServices.Initialize(IServiceProvider scopedProvider, IDbContextOptions contextOptions, DbContext context)
    at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
    at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
    at Microsoft.EntityFrameworkCore.DbContext.get_Model()
    at Microsoft.EntityFrameworkCore.Internal.InternalDbQuery`1.get_EntityType()
    at Microsoft.EntityFrameworkCore.Internal.InternalDbQuery`1.get_EntityQueryable()
    at Microsoft.EntityFrameworkCore.Internal.InternalDbQuery`1.System.Linq.IQueryable.get_Provider()
    at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ExecuteAsync[TSource,TResult](MethodInfo operatorMethodInfo, IQueryable`1 source, CancellationToken cancellationToken)
    at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.SingleAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
    at ... MyMethod(ApplicationDatabaseContext dbContext, CancellationToken cancellationToken) in myfile.cs:line 51
    at ... MyOtherMethod in myfile.cs:line 61

那么,如何转换DbContextOptions或如何继承DbContexts?

1 个答案:

答案 0 :(得分:2)

DbContextOptions<TContext>是通用的,并且作为任何类,它都不支持协方差,因此DbContextOptions<TDerivedContext>不能被视为DbContextOptions<TBaseContext>

解决方案是在基本上下文构造函数中使用 nongeneric DbContextOptions类(类似于带有选项的DbContext类构造函数)

public ApplicationDatabaseContextGenerated(DbContextOptions options) : base(options) { }

由于AddDbContext<ApplicationDatabaseContext>将创建DbContextOptions<ApplicationDatabaseContext>类的实例,因此ApplicationDatabaseContext类的构造函数可以使用DbContextOptions<ApplicationDatabaseContext>DbContextOptions选项参数。