[英]Cannot create migration script using Entity Framework
(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: 当我的dbcontext有无参数构造函数时,我收到以下错误:
No database provider has been configured for this DbContext.
没有为此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: 我将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());
}
}
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 如果这不起作用,请尝试在Startup.cs中注册它
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.