App: Asp.NET Core 1.1.1, EF Core
Platform: Visual Studio 2017 5.3.3
Authentication Mode: Individual User Accounts
Following this tutorial from ASP.NET official team, the following command runs successfully:
PM> Add-Migration MyFirstMigration -context BloggingContext
As we know VS2017
by default creates ApplicationDbContext
under MyProject\Data folder for creating user tables (ASPNETUsers, ASPNETRoles etc...
) for authentication. But for that when I run the following command it first gives me Error-1
below. And when I follow the instructions in first error message, I get Error-2
below. Question: How do I make the following command work without using IDbContextFactory
?
PM> Add-Migration MyFirstAuthenMigration -context ApplicationDbContext
Error 1
No parameterless constructor was found on 'ApplicationDbContext'. Either add a parameterless constructor to 'ApplicationDbContext' or add an implementation of 'IDbContextFactory' in the same assembly as 'ApplicationDbContext'.
After I add a parameterless constructor in ApplicationDbContext.cs
(shown below) I get the second error shown below:
Error 2
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. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.
ApplicationDbContext.cs
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
//NOTE: I added following constructor after Error 1 shown above
public ApplicationDbContext()
{
}
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
}
}
startup.cs
I had replacedservices.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
withvar connection = @"Server=MyMachine\SQLEXPRESS;Database=ForgotPswd;Trusted_Connection=True;"; services.AddDbContext<BloggingContext>(options => options.UseSqlServer(connection));
Is that correct? – nam