问题描述
我正尝试通过使用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
添加默认值约束。列数据类型:
-
newColumn1
:bit
,默认为0 -
newColumn2
:nvarchar(50)
-
newColumn3
:nvarchar(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 (将#修改为@)