(neither of the online resources helped, so I am creating a new thread.)
I am confused with errors I receive when running the following command to create migration scripts:
dotnet ef migrations add InitialCreate -v
I receive the following error when I have parameterless constructor for my dbcontext:
No database provider has been configured for this DbContext.
and when I remove the parameterless constructor, it complains I should put it back:
No parameterless constructor defined for this object
I define the dbcontext as:
public class ItemContext : DbContext
{
public ItemContext(DbContextOptions<ItemContext> options) : base(options)
{
}
public DbSet<Item> Tools { set; get; }
protected override void OnModelCreating(ModelBuilder builder)
{
builder.ApplyConfiguration(new ToolItemEntityTypeConfiguration());
}
}
The Service is defined as:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddCustomDbContext(Configuration);
var container = new ContainerBuilder();
container.Populate(services);
return new AutofacServiceProvider(container.Build());
}
...
public static class CustomExtensionMethods
{
public static IServiceCollection AddCustomDbContext(this IServiceCollection services, IConfiguration configuration)
{
services.AddDbContext<ItemContext>(options =>
{
options.UseSqlServer(configuration.GetConnectionString("DefaultConnection"),
sqlServerOptionsAction: sqlOptions =>
{
sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name);
sqlOptions.EnableRetryOnFailure(maxRetryCount: 10, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
});
options.ConfigureWarnings(warnings => warnings.Throw(RelationalEventId.QueryClientEvaluationWarning));
});
return services;
}
}
I think this line of code
public ItemContext(DbContextOptions<ItemContext> options) : base(options)
{
}
Should change to
public ItemContext(DbContextOptions options) : base(options)
{
}
If this doesnt work for you try to register this in your Startup.cs
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.