Reputation: 331
I've created a dbContext based on an existing Azure SQL Database using Entity Framework. I added this database to my app's services as follows:
public void ConfigureServices(IServiceCollection services)
{
//Identity Database Context
services.AddDbContext<IdentityDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DataDb"),
optionsBuilders =>
optionsBuilders.MigrationsAssembly("WebPortal"))
);
services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<IdentityDbContext>()
.AddDefaultTokenProviders();
//Custom Database Context
services.AddDbContext<CustomDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("CustomDb"))
);
services.AddMvc();
}
When I try to run this I get the following error message:
InvalidOperationException: The DbContextOptions passed to the IdentityDbContext constructor must be a DbContextOptions. When registering multiple DbContext types make sure that the constructor for each context type has a DbContextOptions parameter rather than a non-generic DbContextOptions parameter.
The constructor for my custom Context does have a parameter:
public CustomDbContext(DbContextOptions<CustomDbContext> options)
: base(options)
{
}
Why am I getting the error?
Upvotes: 9
Views: 18217
Reputation: 798
I had the same problem. my scenario was that, i needed two Context ReadDataContext and WriteDataContext,i solved that exception with bottom Contexts
public class ReadOnlyDataContext : DbContext
{
public ReadOnlyDataContext(DbContextOptions options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.RemovePluralizingTableNameConvention();
Assembly assemblyWithConfigurations = typeof(TaskConfiguration).Assembly;
modelBuilder.ApplyConfigurationsFromAssembly(assemblyWithConfigurations);
}
}
Pay attention to the DataContext Constructor
public class WriteDataContext : DbContext, IContext
{
public WriteDataContext(DbContextOptions<WriteDataContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.RemovePluralizingTableNameConvention();
Assembly assemblyWithConfigurations = typeof(TaskConfiguration).Assembly;
modelBuilder.ApplyConfigurationsFromAssembly(assemblyWithConfigurations);
}
}
And for registeration
services.AddDbContext<DataContext>(opt =>
{
opt.UseSqlServer(configuration.GetConnectionString("CommanderConnection"));
opt.LogTo(Console.WriteLine).EnableSensitiveDataLogging();
});
services.AddDbContext<ReadOnlyDataContext>(opt =>
{
opt.UseSqlServer(configuration.GetConnectionString("CommanderConnection"));
opt.LogTo(Console.WriteLine).EnableSensitiveDataLogging();
});
Upvotes: 9