Search code examples
entity-frameworkasp.net-coreopenid-connectaspnet-contribopeniddict

Configure DbContext for OpenIddict


I'm using OpenIddict for JWT token authentication in my .NET Core app. I've followed this tutorial but I am now receiving the following error:

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...

My ConfigureServices method in Startup.cs:

        public void ConfigureServices(IServiceCollection services)
    {
        var builder = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json");
        Configuration = builder.Build();

        services.AddEntityFrameworkSqlServer()
             .AddDbContext<MyDbContext>(options =>
                 options.UseSqlServer(Configuration["Data:MyDbContext:ConnectionString"]));

        services.AddIdentity<ApplicationUser, ApplicationRole>()
            .AddEntityFrameworkStores<MyDbContext>()
            .AddDefaultTokenProviders()
            .AddOpenIddictCore<Application>(config => config.UseEntityFramework());

        services.AddMvc();

        // for seeding the database with the demo user details
        //services.AddTransient<IDatabaseInitializer, DatabaseInitializer>();
        services.AddScoped<OpenIddictManager<ApplicationUser, Application>, CustomOpenIddictManager>();
    }

Not sure what to do about this as I can't add a DbContext when using AddIdentity.

My connection string is fine, everything was working before adding OpenIddict.

UPDATE Here is my appsettings.json file:

    {
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Verbose",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "Data": {
    "DefaultConnection": {
      "ConnectionString": "my connection string"
    },
    "SaleboatContext": {
      "ConnectionString": "my connection string"
    }
  }
}

My DbContext:

public class ApplicationUser : IdentityUser { }

public partial class MyDbContext : IdentityDbContext<ApplicationUser>
{

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
}

Solution

  • Due to a design change in EntityFramework Core RC2, you now need to flow the DbContextOptions manually or configure your connection string directly in OnModelCreating.

    Try adding this constructor to your DB context (that should derive from OpenIddictContext):

    public partial class MyDbContext : OpenIddictContext<ApplicationUser> {
        public MyDbContext(DbContextOptions options)
            : base(options) {
        }
    }