Search code examples
c#asp.net-core.net-core.net-core-3.0.net-core-3.1

Unable to create an object of type 'ApplicationDbContext'. For the different patterns supported at design time


I face the following error when adding the migration of database in .net core

This is the error:

This is the code in Startup:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options => 
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
           
    services.AddDefaultIdentity<ApplicationUser>().AddEntityFrameworkStores<ApplicationDbContext>();
    services.AddControllers();
}

This is the ApplicationDbContext class:

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

    public DbSet<ApplicationUser> applicationUsers { get; set; }
}

This is the ApplicationUser:

public class ApplicationUser : IdentityUser
{
    [Required]
    [Column(TypeName = "nvarchar(150)")]
    public string UserFName { get; set; }
    [Required]
    public string UserLName { get; set; }
}

Solution

  • Seems you are your inheritance is wrong.

    public ApplicationDbContext : IdentityDbContext
    

    should be

    public ApplicationDbContext : IdentityDbContext<ApplicationUser>
    

    or

    public ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole>
    

    if you also extend roles class.

    when you want to create an context with an extended user class (instead of IdentityUser)