(这两个在线资源都无济于事,所以我正在创建一个新线程。)
我对运行以下命令来创建迁移脚本时收到的错误感到困惑:
dotnet ef migrations add InitialCreate -v
当我的dbcontext具有无参数构造函数时,出现以下错误:
尚未为此DbContext配置数据库提供程序。
当我删除无参数构造函数时,它抱怨我应该放回原处:
没有为此对象定义无参数构造函数
我将dbcontext定义为:
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());
}
}
服务定义为:
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;
}
}
答案 0 :(得分:0)
我认为这行代码
public ItemContext(DbContextOptions<ItemContext> options) : base(options)
{
}
应更改为
public ItemContext(DbContextOptions options) : base(options)
{
}
如果这对您不起作用,请尝试在Startup.cs中注册它。
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();