beloud
beloud

Reputation: 95

Cannot solve this error, "No database provider has been configured for this DbContext"

I have recently come back to ASP.Net after a long break, and have been experimenting with web app development using Core 2.1.

Visual Studio 2019

I have followed one of the 'beginning' guides on Microsoft's website, and I am having problems with the data provider for the connection string to SQLExpress.

I keep getting the error "No database provider has been configured for this DbContext", when I try and access SQLExpress.

Full error

An unhandled exception occurred while processing the request.
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.
Microsoft.EntityFrameworkCore.Internal.DbContextServices.Initialize(IServiceProvider scopedProvider, IDbContextOptions contextOptions, DbContext context)

Stack Query Cookies Headers
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.
Microsoft.EntityFrameworkCore.Internal.DbContextServices.Initialize(IServiceProvider scopedProvider, IDbContextOptions contextOptions, DbContext context)
Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
Microsoft.EntityFrameworkCore.DbContext.get_Model()
Microsoft.EntityFrameworkCore.Internal.InternalDbSet<TEntity>.get_EntityType()
Microsoft.EntityFrameworkCore.Internal.InternalDbSet<TEntity>.get_EntityQueryable()
Microsoft.EntityFrameworkCore.Internal.InternalDbSet<TEntity>.System.Linq.IQueryable.get_Provider()
Microsoft.EntityFrameworkCore.RelationalQueryableExtensions.FromSql<TEntity>(IQueryable<TEntity> source, RawSqlString sql, object[] parameters)
SQL_Connection_2.Pages.ContactModel.OnGet() in Contact.cshtml.cs
Microsoft.AspNetCore.Mvc.RazorPages.Internal.ExecutorFactory+VoidHandlerMethod.Execute(object receiver, object[] arguments)
Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.InvokeHandlerMethodAsync()
Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.InvokeNextPageFilterAsync()
Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.Rethrow(PageHandlerExecutedContext context)
Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.InvokeInnerFilterAsync()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Startup.cs

public void ConfigureServices(IServiceCollection services) {
            services.Configure<CookiePolicyOptions>(options => {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddDbContext<ConfigurationContext>(options => {
                options.UseSqlServer(Configuration.GetConnectionString("MyConnection"));
            });
        }

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "MyConnection": "server=.\\SQLExpress;database=WebApp_Test;trusted_connection=true;"
  }
}

ConfigurationContext.cs

public class ConfigurationContext:DbContext {

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


        public DbSet<Person> Persons { get; set; }

    }

If I change the code in ConfigurationContext.cs to (below) everything works, but this is bypassing the connection string in appsettings.json, so it does not seem as though services.AddDbContext is executing in the Startup.cs file.

public class ConfigurationContext : DbContext {

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
            optionsBuilder.UseSqlServer(@"Server=.\SQLExpress;Database=WebApp_Test;Trusted_Connection=True;MultipleActiveResultSets=true;");
        }

    }

Can anyone offer any advice on how to fix this? Ideally I want the connection string configured in the appsettings.json file.

I have spent many hours trying to fix this, looking for that discovery and learning moment.

Upvotes: 2

Views: 13651

Answers (2)

Asherguru
Asherguru

Reputation: 1741

Startup.cs, add ConnectionService.Set

public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
        ConnectionService.Set(configuration);
    }

ConnectionService.cs

public static string connstring = "";
public static string Set(IConfiguration config)
    {
        connstring = config.GetConnectionString("MyConnection");
    }

ConfigurationContext.cs

public class ConfigurationContext : DbContext {

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
        optionsBuilder.UseSqlServer(ConnectionService.connstring);
    }

}

Upvotes: 2

bsod_
bsod_

Reputation: 941

Try using the connection string you have used within your OnConfiguring method, as what you have posted they are different.

Like this -

  "ConnectionStrings": {
    "MyConnection": "Server=.\SQLExpress;Database=WebApp_Test;Trusted_Connection=True;MultipleActiveResultSets=true;"
  }

Upvotes: 1

Related Questions