gpt4 book ai didi

c# - 无法使用 Entity Framework 创建迁移脚本

转载 作者:行者123 更新时间:2023-11-30 18:11:32 25 4
gpt4 key购买 nike

(在线资源都没有帮助,所以我创建了一个新线程。)

我对运行以下命令创建迁移脚本时收到的错误感到困惑:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com