add-migration在数据库中查询我要添加的列,失败并显示“错误:无效的列名'newColumn1','newColumn2','newColumn3'”

问题描述

我正尝试通过使用EF Core(软件包版本3.1.8)进行代码优先迁移,将三列添加到现有表中。当我运行add-migration <name> -c <context> -o <output folder>时,它会抛出此错误(以及大量的堆栈跟踪...):

An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the 
application service provider. Error: Invalid column name 'NewColumn1'.
Invalid column name 'NewColumn2'.
Invalid column name 'NewColumn3'.
Unable to create an object of type 'MyDbContext'. For the different patterns supported at 
design time,see https://go.microsoft.com/fwlink/?linkid=851728

对此感到困惑。这是我今天添加的第四次迁移,以前的迁移都没有这个问题。

此迁移应添加三列,这些列的预定义行的数据,并向newColumn1添加认值约束。列数据类型:

  • newColumn1bit认为0
  • newColumn2nvarchar(50)
  • newColumn3nvarchar(50)

添加麻烦迁移之前的我的实体:

public class MyEntity
{
    [Key]
    public int Id { get; set; }

    [MaxLength(50),required]
    public string AttributeName { get; set; }

    [required]
    public bool required { get; set; }
}

在尝试添加此迁移之前,此实体更改为以下内容

public class MyEntity
{
    [Key]
    public int Id { get; set; }

    [MaxLength(50),required]
    public string AttributeName { get; set; }

    [required]
    public bool required { get; set; }

    public bool NewColumn1{ get; set; }

    [MaxLength(50)]
    public string NewColumn2 { get; set; }

    [MaxLength(50)]
    public string NewColumn3 { get; set; }
}

MyDbContext.OnModelCreating中,我有以下新代码

builder.Entity<MyEntity>().Property(x => x.NewColumn1).HasDefaultValue(false);

如前所述,IEntityTypeConfiguration<MyEntity>也已更新为具有预定义行的所有新列的数据。除了预定义的行,数据库中没有其他行。

我对发生的事情有一个理论。我认为add-migration需要一个MyDbContext的实例,并且在实例化它时,它会验证数据库是否符合预期的样子。上下文期望由MyEntity表示的表具有在实体中定义的三个新列,但它们在数据库中不存在。我很好奇的是为什么现在才开始呢?这是我今天的第四次迁移,我的其他迁移都添加了表,列,数据...。为什么这现在才开始成为问题?

错误中的msft文档链接使我认为我需要实现IDesignTimeDbContextFactory<MyDbContext>,以使其不会阻塞的方式对其进行配置。但是从DbContextOptionsBuilder的行为来看,它提供的任何选项都不会让我绕过我得到的行为。

数据库已使用以前的所有迁移进行了更新,我检查了DbContextModelSnapshot文件...新列不在此处的任何位置(按预期)。我定位的数据库是本地sql Server数据库

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)