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

标签 c# entity-framework asp.net-core .net-core

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

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

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/

相关文章:

c# - 将数据从远程服务器拉到本地服务器......最好,最安全的方式

c# - 在 Xamarin Forms 的导航页面中添加搜索栏

c# - 是否可以将 DataTable 传递给 Entity Framework 中的临时 sql 查询?

linq - Entity Framework linq 查询 Include() 多个子实体

asp.net-core - 如何统计 ASP.NET Core 2.0 中具有特定角色的所有用户

c# - Asp.net Core Identity 单元测试 Controller 操作

c# - 如何从我的数据库(formview)中检索数据并将其相乘,visual studio

c# - OnActionExecuted 和 OnResultExecuting 之间的区别

c# - Fluent API、一对一关系和级联删除

asp.net-core - 使用托管生成代理从 Visual Studio Team Services 发布 ASP.NET 5 RC1 项目时出错