繁体   English   中英

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

[英]Cannot create migration script using Entity Framework

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

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

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;
    }
}

我想这行代码

public ItemContext(DbContextOptions<ItemContext> options) : base(options)
{

}

应该改为

public ItemContext(DbContextOptions options) : base(options)
{

}

如果这不起作用,请尝试在Startup.cs中注册它

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM