當使用 EF Code First 設計資料表時,如果有一個欄位是要設定計算公式時,程式碼該如何寫呢?
以下幾個步驟
- 
在欄位上標記欄位屬於 computed性質1 
 2
 3
 4[] 
 public int CalculatedField {
 get; private set;
 }
- 
新增 migration1 add-migration xxxx-xxxx 
- 
打開剛建立的 migration檔案並找到剛剛所指定的欄位1 
 2
 3
 4
 5
 6
 7
 8
 9migrationBuilder.CreateTable( 
 name: "Demo",
 columns: table => new
 {
 // 刪除原本產生的欄位
 CalculatedField = table.Column<int>(nullable: false, defaultValue: 0),
 },
 );
 migrationBuilder.Sql("ALTER TABLE dbo.Demo ADD CalculatedField AS ([你的計算規則])");
- 
打完收工 
以上是我目前的作法,能正常運作。如果有更好的寫法,也歡迎在下面留言分享討論
額外補充
如果想要透過 EF Migration 來新增 Stored Procedure 的話,可以這樣子寫
- 
將 storeㄎ procedure 的 SQL 檔案放在某資料夾下,並將 SQL 檔案設定為 內嵌資源 (EmbeddedResource)
- 
新增一個空的 migration 後加入以下的程式碼 1 
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21protected override void Up(MigrationBuilder migrationBuilder) 
 {
 var assembly = Assembly.GetExecutingAssembly();
 var resourceNames =
 assembly.GetManifestResourceNames().
 Where(str=> str.Contains("[sp file name].sql"));
 foreach (string resourceName in resourceNames)
 {
 using (Stream stream = assembly.GetManifestResourceStream(resourceName))
 using (StreamReader reader = new StreamReader(stream))
 {
 string sql = reader.ReadToEnd();
 migrationBuilder.Sql(sql);
 }
 }
 }
 protected override void Down(MigrationBuilder migrationBuilder)
 {
 migrationBuilder.Sql("DROP PROCEDURE [SP Name]");
 }
- 
當進行 database 更新時,就會將該 SP 新增到資料庫中