簡體   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