簡體   English   中英

代碼優先遷移 - 實體框架 - 無法向表中添加列

[英]Code First Migration - Entity Framework - unable to add column to the table

這個問題已經多次以不同的口味問過SO。 我已經完成了所有的答案,並且耗費了大量的時間。 我似乎無法讓這個工作。

我一直在研究asp.net mvc Entity Framework,SQL server app。 我已經有了一個現有的數據庫,表格等,而且每件事都有效。 我只需要在表格中添加一個新列。

所以..我在模型類中添加了一個屬性,以便我可以將列添加到表中。 但沒有成功。

所以我按以下順序執行這些步驟。

  1. 在我的模型類中添加字段。

     [Required] public string EmailSubject{ get; set; } 
  2. 然后我刪除包含Configuration.cs類的asp.net mvc項目中的遷移文件夾
  3. 然后在Package Manager Console中,我成功發出以下命令。

     Enable-Migrations -ContextTypeName AppointmentReminder.Data.ReminderDb -Force 
  4. 然后我將屬性設置為true,如下所示

     public Configuration() { AutomaticMigrationsEnabled = true; } 
  5. 然后我在包管理器控制台中發出以下命令。

     Update-Database -Verbose -Force 

以下是我與數據庫的默認連接的連接字符串

Data Source=(LocalDb)\v11.0;AttachDbFilename=C:\practice\AppointmentReminder4\AppointmentReminder4\App_Data\aspnet-AppointmentReminder4-20141202060615.mdf;Initial Catalog=aspnet-AppointmentReminder4-20141202060615;Integrated Security=True

但我無法在我想要的表中添加新列。


編輯1

我更新了模型如下,沒有必需的屬性,並執行了上述所有步驟,但我仍然無法將列添加到表中。

public string EmailBody { get; set; }

以下是所有命令及其輸出。

PM> Enable-Migrations -ContextTypeName AppointmentReminder.Data.ReminderDb -Force
Checking if the context targets an existing database...
Code First Migrations enabled for project AppointmentReminder4.
PM> Update-Database -Verbose -Force
Using StartUp project 'AppointmentReminder4'.
Using NuGet project 'AppointmentReminder4'.
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Target database is: 'aspnet-AppointmentReminder4-20141202060615' (DataSource: (LocalDb)\v11.0, Provider: System.Data.SqlClient, Origin: Configuration).
No pending explicit migrations.
Running Seed method.
PM> Update-Database -Verbose -Force
Using StartUp project 'AppointmentReminder4'.
Using NuGet project 'AppointmentReminder4'.
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Target database is: 'aspnet-AppointmentReminder4-20141202060615' (DataSource: (LocalDb)\v11.0, Provider: System.Data.SqlClient, Origin: Configuration).
No pending explicit migrations.
Running Seed method.
PM> 

編輯2最后解決了這個問題。 我上面的所有步驟都是正確的。 除了我正在編輯我的模型類,而不是實際綁定到ReminderDb(EF對象)的實際數據類。 在我用屬性更新了正確的類之后,每件事都成功了。 感謝所有回復幫助的人!

由於該字段是必需的,因此您需要指定默認值。 編輯遷移文件,找到添加列的行,並指定默認值應為:

public override void Up()
{    
    AddColumn("dbo.MyTable", "EmailSubject", c => c.String(nullable: false, defaultValue: ""));
}

供參考: Entity Framework遷移中必填字段的默認值?

編輯:根據您的編輯,您需要在嘗試更新之前創建遷移。 請參閱此示例 ,了解您通常如何使用它。

但是,如果您嘗試將代碼優先遷移應用於現有數據庫,本文可能會有所幫助: 使用現有數據庫進行代碼優先遷移

您使用required屬性修飾了新列。 如果該表已經有一些行,則這些行不能包含該列。 刪除所需。 比遷移,用數據填充所有行。 使屬性成為必需並再次遷移。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM