使用 EF 迁移将现有数据库列添加到模型

Add existing DB column to model with EF migration

在数据库中有一个列 Created,它有一个默认值 GETDATE(),所以它是在插入时自动分配的。此列当前不在模型 class 中。当我尝试将 属性 添加到模型时 class:

[Required, DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime Created { get; set; }

和 运行 update-database,结果是消息:

Unable to update database to match the current model because there are pending changes and automatic migration is disabled. Either write the pending model changes to a code-based migration or enable automatic migration. Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic migration. You can use the Add-Migration command to write the pending model changes to a code-based migration.

当我尝试允许自动迁移时,EF 尝试创建数据库列 Created,但这失败了,因为该列已经存在。

有没有办法修正模型class?

使用 -IgnoreChanges 创建空迁移并应用于数据库。

Add-Migration AddsCreatedProperty -IgnoreChanges
Update-Database

您还希望为迁移中 bootstrap 的任何其他数据库添加该列。因此,在您的空迁移中,在 Up 方法

中添加 sql 语句
SQL(@"
    IF NOT EXISTS (
      SELECT *  FROM   sys.columns  WHERE  
        object_id = OBJECT_ID(N'[dbo].[MyTable]')  AND name = 'Created'
    )
    BEGIN
        ALTER TABLE MyTable
        ADD Created DATETIME NOT NULL DEFAULT (GETDATE());
    END
");