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

eman picture eman · Jan 18, 2020 · Viewed 12.6k times · Source

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; }
}

Answer

AFetter picture AFetter · May 24, 2020

I found the cause of this error could be multiple things in your code. For me at least, the best way was to add verbose in command.

With that will be able to understand what is the problem. the verbose will display all steps of the execution.

In visual studio use:

add-migration Added_something -verbose

For the CLI use:

dotnet ef migrations add Added_something  --verbose