繁体   English   中英

将 IdentityDbContext 替换为常规 DbContext 后的迁移问题

[英]Migration issues after replacing IdentityDbContext with regular DbContext

最初我使用 IdentityDbContext 有一段时间了。 一切正常,我正在进行迁移等。 但最近我决定让 AWS Cognito 处理用户和密码,因此不再需要 IdentityDbContext。 所以我将我的 ApplicationDbContext class 改为继承 DbContext 。

我清除了迁移和快照,杀死并修剪了 docker 容器。 一旦我尝试进行初始迁移,我会在 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 的 class 并且我实际上能够添加迁移,但第一个错误仍然存在:

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 Class 所在的项目不同,但它由 docker-compose 容器化。

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

当我运行迁移命令时,我 select 默认项目为 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.

最终成为 Program.cs 文件中的 AWS 配置,我没有将我的 AWS 配置文件传递给 AWSOptions class。

暂无
暂无

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

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