(在线资源都没有帮助,所以我创建了一个新线程。)
我对运行以下命令创建迁移脚本时收到的错误感到困惑:
dotnet ef migrations add InitialCreate -v
当我为我的 dbcontext 使用无参数构造函数时,我收到以下错误:
No database provider has been configured for this DbContext.
当我删除无参数构造函数时,它会提示我应该把它放回去:
No parameterless constructor defined for this object
我将 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;
}
}
最佳答案
我觉得这行代码
public ItemContext(DbContextOptions<ItemContext> options) : base(options)
{
}
应该改为
public ItemContext(DbContextOptions options) : base(options)
{
}
如果这对您不起作用,请尝试在您的 Startup.cs 中注册
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
关于c# - 无法使用 Entity Framework 创建迁移脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57825321/