Search code examples
c#authenticationoauth-2.0asp.net-identityopeniddict

Can't resolve "Cannot create DbSet for 'OpenIddictEntityFrameworkCoreApplication" because this type is not included in the model for the context."


I'm using the authorization code flow with the OpenIddict library and I'm getting an "InvalidOperationException" with the following message: "Cannot create DbSet for 'OpenIddictEntityFrameworkCoreApplication' because this type is not included in the model for the context." message. This message is thrown when trying to run the application.

Error Message

I've found some solutions online, although none have been able to resolve my issue.

Here's my startup configuration and DbContext. I'm using the default identity models in ASPNet Core 6.

Program.cs

builder.Services.AddOpenIddict()

    // Register the OpenIddict core components.
    .AddCore(options =>
    {
        // Configure OpenIddict to use the Entity Framework Core stores and models.
        // Note: call ReplaceDefaultEntities() to replace the default entities.
        options.UseEntityFrameworkCore()
               .UseDbContext<ApplicationDbContext>();
    })

    // Register the OpenIddict server components.
    .AddServer(options =>
    {
        // Enable the client credentials flow.
        options.AllowClientCredentialsFlow();

    // Enable the authorization code flow.
    options.AllowAuthorizationCodeFlow().RequireProofKeyForCodeExchange();

    // Enable the token endpoint.
    options.SetAuthorizationEndpointUris("/connect/authorize")
        .SetTokenEndpointUris("/connect/token");

    // Register the signing and encryption credentials.
    options.AddDevelopmentEncryptionCertificate()
          .AddDevelopmentSigningCertificate();

    // Register scopes (permissions)
    options.RegisterScopes("api");

    // Register the ASP.NET Core host and configure the ASP.NET Core options.
    options.UseAspNetCore()
          .EnableTokenEndpointPassthrough()
          .EnableAuthorizationEndpointPassthrough();
    })

    // Register the OpenIddict validation components.
    .AddValidation(options =>
    {
        // Import the configuration from the local OpenIddict server instance.
        options.UseLocalServer();

    // Register the ASP.NET Core host.
    options.UseAspNetCore();
    });

ApplicationDbContext.cs

public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options): base(options) {   }

I've yet to find why I'm receiving this issue. Any help would be great. Thanks.


Solution

  • The problem was within my startup configuration. I found 2 calls to the following method like so...

    builder.Services.AddDbContext<ApplicationDbContext>(options => 
      options.UseSqlServer(connectionString));
    builder.Services.AddDbContext<ApplicationDbContext>(options =>
    {
        options.UseSqlServer(connectionString);
        options.UseOpenIddict();
    });
    

    I removed the first method call and the exception went away.