InvalidOperationException:没有为此DbContext配置数据库提供程序。可以通过覆盖DbContext

时间:2019-02-28 10:14:52

标签: c# entity-framework asp.net-core dbcontext

我正在从事没有存储库模式的项目。我试图将我的业务逻辑与控制器分开,这是建立业务层的一种方式。我执行以下操作以获取所有用户。

DbContext

public class DatabaseContext : DbContext
{
    public DatabaseContext() : base() { }
    public DatabaseContext(DbContextOptions options) : base(options) { }
    public DbSet<User> Users { get; set; }
    public DbSet<OvertimeRequest> OvertimeRequests { get; set; }
    public DbSet<HolidayRequest> HolidayRequests { get; set; }
    public DbSet<PaymentRequest> PaymentRequests { get; set; }
}

OvertimeRequestBusiness

public class OvertimeRequestBusiness
{
    public static OvertimeRequestBusiness Instance { get; } = new 
        OvertimeRequestBusiness();

    public OvertimeRequestBusiness() { }

    public async Task<List<User>> GetAllUsersAsync()
    {
        using (var ctx = new DatabaseContext())
        {
            var query = ctx.Users;
            var res = await query.ToListAsync();
            return res;
        }
    }
}

控制器

[Route("users"), HttpGet]
public async Task<List<User>> GetAllUsers()
{
    return await OvertimeRequestBusiness.Instance.GetAllUsersAsync();
}

我得到的错误是

  

InvalidOperationException:没有为此DbContext配置数据库提供程序。可以通过重写DbContext.OnConfiguring方法或在应用程序服务提供程序上使用AddDbContext来配置提供程序。如果使用AddDbContext,则还请确保您的DbContext类型在其构造函数中接受DbContextOptions 对象,并将其传递给DbContext **的基本构造函数。

3 个答案:

答案 0 :(得分:1)

不更改OvertimeRequestBusiness就是在OnCongfiguring类的DbContext方法中设置数据库连接字符串:

  1. 在`appsettings.json中设置连接字符串:

    "ConnectionStrings": {
        "MyConnectionString": "Server=(localdb)\\mssqllocaldb;Database=RazorPagesMovieContext-1234;Trusted_Connection=True;MultipleActiveResultSets=true"
    },
    
  2. 创建Setting.cs

    public class Setting
    {
        public static string ConnectionString { get; set; }
    }
    
  3. Startup.cs中配置连接字符串:

    Setting.ConnectionString = Configuration.GetSection("ConnectionStrings:MyConnectionString").Value;
    
  4. 修改DatabaseContext

    public class DatabaseContext : DbContext
    {
    
          public DbSet<User> Users { get; set; }
          public DbSet<OvertimeRequest> OvertimeRequests { get; set; }
          public DbSet<HolidayRequest> HolidayRequests { get; set; }
          public DbSet<PaymentRequest> PaymentRequests { get; set; }
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlServer(Setting.ConnectionString);
            }
        }
    
    }
    

但是常见的方法是将DbContext与依赖项注入一起使用:

https://docs.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext

答案 1 :(得分:0)

您的DatabaseContext构造函数需要指向连接字符串。

将其更改为

public class DatabaseContext : DbContext
{
    // Tell DbContext to look for the "MyConnectionString" in .config.
    public DatabaseContext() : base("MyConnectionString") { }

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

    public DbSet<User> Users { get; set; }
    public DbSet<OvertimeRequest> OvertimeRequests { get; set; }
    public DbSet<HolidayRequest> HolidayRequests { get; set; }
    public DbSet<PaymentRequest> PaymentRequests { get; set; }
}

您的连接字符串在web.config中

<configuration>
    <connectionStrings>
        <add name="MyConnectionString" providerName="System.Data.SqlClient" connectionString="Server=.\SQLEXPRESS;Initial Catalog=ABC;Integrated Security=True;MultipleActiveResultSets=true"></add>
    </connectionStrings>
</configuration>

答案 2 :(得分:0)

我删除了DbContext的默认无参数构造函数,然后将DbContextBuilderOption传递为OvertimeRequestBusiness中的参数。这对我有用。

OvertimeRequestBusiness现在看起来像这样

 public class OvertimeRequestBusiness
    {
        public static OvertimeRequestBusiness Instance { get; } = new OvertimeRequestBusiness();

        DbContextOptionsBuilder<DatabaseContext> _optionsBuilder;


        public OvertimeRequestBusiness() {
            var optionsBuilder = new DbContextOptionsBuilder<DatabaseContext>();
            optionsBuilder.UseSqlServer(@"ConnectionString");
            _optionsBuilder = optionsBuilder;
        }
  public async Task<List<User>> GetAllUsersAsync()
        {
            using (var ctx = new DatabaseContext(_optionsBuilder.Options))
            {
                var query = ctx.Users;
                var res = await query.ToListAsync();
                return res;
            }
        }

    }