带有 dbcontextoptions 的构造函数不起作用,无法创建上下文实例
constructor with dbcontextoptions not working, unable to create instance of context
刚刚创建了一个新的 dotnet web 应用程序,还不能完全创建我的数据库。
在我的基础架构层中,我添加了一个 dbcontext :
public class SurveyContext : DbContext
{
public SurveyContext(DbContextOptions<SurveyContext> options) : base(options)
{
}
public DbSet<Survey> Surveys { get; set; }
public DbSet<Question> Questions { get; set; }
public DbSet<Answer> Answers { get; set; }
}
在API、Program.cs中我添加了这个:
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<SurveyContext>(x => x.UseSqlite(connectionString));
我尝试创建迁移,但出现此错误
Unable to create an object of type 'SurveyContext'
为了避免 IDesignTimeDbContextFactory,我在注入中添加了默认构造函数 (public SurveyContext(){}
) 和 ServiceLifetime.Transient
,如 here 所示。但是现在我得到了另一种错误
No database provider has been configured for this DbContext. A provider can be configured by overriding the 'DbContext.OnConfiguring' method or by using 'AddDbContext' on the application service provider. If 'AddDbContext' is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.
我以前从来没有遇到过这种问题。有人可以指导我了解我做错了什么吗?
原来我在安装包时出错了。我在基础设施项目中有 EntityFrameworkCore.Design 而不是 API。
刚刚创建了一个新的 dotnet web 应用程序,还不能完全创建我的数据库。
在我的基础架构层中,我添加了一个 dbcontext :
public class SurveyContext : DbContext
{
public SurveyContext(DbContextOptions<SurveyContext> options) : base(options)
{
}
public DbSet<Survey> Surveys { get; set; }
public DbSet<Question> Questions { get; set; }
public DbSet<Answer> Answers { get; set; }
}
在API、Program.cs中我添加了这个:
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<SurveyContext>(x => x.UseSqlite(connectionString));
我尝试创建迁移,但出现此错误
Unable to create an object of type 'SurveyContext'
为了避免 IDesignTimeDbContextFactory,我在注入中添加了默认构造函数 (public SurveyContext(){}
) 和 ServiceLifetime.Transient
,如 here 所示。但是现在我得到了另一种错误
No database provider has been configured for this DbContext. A provider can be configured by overriding the 'DbContext.OnConfiguring' method or by using 'AddDbContext' on the application service provider. If 'AddDbContext' is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.
我以前从来没有遇到过这种问题。有人可以指导我了解我做错了什么吗?
原来我在安装包时出错了。我在基础设施项目中有 EntityFrameworkCore.Design 而不是 API。