最初我使用IdentityDbContext有一段时间了。一切正常,我在做移民之类的事情。但是最近我决定让AWS认知来处理用户和密码,这样就不再需要IdentityDbContext了。因此,我将我的ApplicationDbContext类改为继承DbContext。
我清理了迁移和快照,杀死并修剪了码头集装箱。一旦我尝试进行初始迁移,就会在Package控制台中得到以下错误:
An error occurred while accessing the Microsoft.Extensions.Hosting services.
Continuing without the application service provider.
Error: Object reference not set to an instance of an object.
Unable to create an object of type 'ApplicationDbContext'.
For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
在进行了一些研究之后,我添加了一个继承IDesignTimeDbContextFactory的类,实际上我能够添加迁移,但是第一个错误仍然存在:
An error occurred while accessing the Microsoft.Extensions.Hosting services.
Continuing without the application service provider.
Error: Object reference not set to an instance of an object.
我的项目结构已经设置好了,所以启动文件在一个与ApplicationDbContext类不同的项目中,但是它是由docker编写的。
Project.Api
- Startup.cs
- Program.cs
Project.App
- ApplicationDbContext.cs
- Migrations Folder
下面是我如何在Startup.cs中添加数据库:
var connectionString = Configuration.GetSection("ConnectionStrings").GetSection("DefaultConnection").Value;
services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseNpgsql(connectionString,
b =>
{
b.MigrationsAssembly("Project.App");
});
});
ApplicationDbContext.cs是什么样子的:
public ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options){}
// DbSet<Entities>...
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// ...
// ...
}
}
public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
{
private readonly DbConfig _dbConfig;
public ApplicationDbContextFactory(IOptionsMonitor<DbConfig> dbConfig)
{
_dbConfig = dbConfig.CurrentValue;
}
public ApplicationDbContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
optionsBuilder.UseNpgsql(_dbConfig.DefaultConnection);
return new ApplicationDbContext(optionsBuilder.Options);
}
}
在运行迁移命令时,我选择默认项目为Project.App,并在Package控制台中编写:
Add-Migration initMigration -Context ApplicationDbContext -Project Project.App -StartupProject Project.Api.
如前所述,在包含了DbContextFactory之后,它只显示了这个错误:
An error occurred while accessing the Microsoft.Extensions.Hosting services.
Continuing without the application service provider.
Error: Object reference not set to an instance of an object.
发布于 2022-07-29 16:35:13
最后是Program.cs文件中的AWS配置,而不是将AWS配置文件传递给AWSOptions类。
https://stackoverflow.com/questions/73130219
复制相似问题