使用Base实现asp.net core 2.0将D添加到DbContext

时间:2018-03-15 14:45:04

标签: c# dependency-injection asp.net-core-2.0 asp.net-core-webapi

我有我的DbContext的基本实现,如下所示;

public abstract class DataContext : IdentityDbContext<ApplicationUser, ApplicationRole, int>, IDataContext
{
    public DataContext(DbContextOptions<DataContext> options)
    : base(options)
    {
    }

我的实施是

public class MyDataContext : DataContext, IMyDataContext
{
    public MyDataContext(DbContextOptions<DataContext> options)
    : base(options)
    {

    }

现在运行迁移时,我使用以下(成功);

public class MyContextFactory : IDesignTimeDbContextFactory<MyDataContext>
{
    public MyContextFactory()
    {
    }

    public MyDataContext CreateDbContext(string[] args)
    {
        var builder = new DbContextOptionsBuilder<DataContext>();
        builder.UseSqlServer(DbGlobals.DevDatabase);

        return new MyDataContext(builder.Options);
    }
}

然而,当我尝试在我的WebApi Startup.cs中设置DbContext时,我添加如下;

        services.AddDbContext<MyDataContext>(
            options => options.UseSqlServer(DbGlobals.DevDatabase));

然而,当我运行这个时,我得到以下错误;

  

System.InvalidOperationException:无法解析类型&#39; Microsoft.EntityFrameworkCore.DbContextOptions`1 [MyProject.Data.DataContext]&#39;在尝试激活MyProject.Data.EF.MyDataContext&#39;。

我认为它试图注入DbContextOptions<MyDataContext>而不是DbContextOptions<DataContext>。我如何解决它,以便传递正确的DbContextOptions?

或者,如果我将MyDbContext类构造函数调整为DbContextOptions<MyDataContext>,那么如何将其转换为基础实现呢?

2 个答案:

答案 0 :(得分:0)

基于我在这里找到的主题

EntityFrameworkCore Issues

通过将DataContext基类设置为;

public abstract class DataContext : IdentityDbContext<ApplicationUser, ApplicationRole, int>, IDataContext
{
    public DataContext(DbContextOptions options)
    : base(options)
    {
    }

然后在MyDataContext上

public class MyDataContext : DataContext, IMyDataContext
{
    public MyDataContext(DbContextOptions<DataContext> options): base(options)
    {

    }

然后依赖注入工作。

答案 1 :(得分:0)

就我而言,我正在使用如下构造函数:

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

我刚刚使用了非通用的DbContextOptions,我的问题就消失了:

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