Search code examples
asp.netentity-framework-6asp.net-identity.net-6.0

Can't add IdentityDbContext along with DbContext in .NET 6


I was trying to upgrade a .NET 5 project to .NET 6. While trying to add multiple db context in Program.cs file, I got some errors.

builder.Services.AddDbContext<StoreContext>(opt =>
{
    opt.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection"));
});
builder.Services.AddDbContext<AppIdentityDbContext>(opt =>
{
    opt.UseSqlite(builder.Configuration.GetConnectionString("IdentityConnection"));
});

StoreContext is derived from DbContext(Microsoft.EntityFrameworkCore package) which is fine. But AppIdentityDbContext which is derived from IdentityDbContext(Microsoft.AspNetCore.Identity.EntityFrameworkCore package) gives the following errors:

  • The type 'Infrastucture.Identity.AppIdentityDbContext' cannot be used as type parameter 'TContext' in the generic type or method 'EntityFrameworkServiceCollectionExtensions.AddDbContext(IServiceCollection, Action?, ServiceLifetime, ServiceLifetime)'. There is no implicit reference conversion from 'Infrastucture.Identity.AppIdentityDbContext' to 'Microsoft.EntityFrameworkCore.DbContext'.

  • Entity Framework Core does not support multiple parallel operations being run on the same DbContext instance. This includes both parallel execution of async queries and any explicit concurrent use from multiple threads. Therefore, always await async calls immediately, or use separate DbContext instances for operations that execute in parallel. See Avoiding DbContext threading issues for more information.

Here is my full project: https://github.com/trktuhin/skinet/


Solution

  • Finally I found what was wrong. My API project was missing a library which should come automatically with latest template. That is :

    Microsoft.AspNetCore.Authentication.JwtBearer
    

    I had to manually install this package in my API project. That solved my issue.