前往
大廳
主題

【.NET 6 /.NET CORE】談談那些坑 產生錯誤的模型 和 SqlNullValueException

伶乃 | 2022-01-09 22:58:14 | 巴幣 10 | 人氣 230

產生錯誤的模型

總之 在有外鍵的情況下會發生資料連接的問題,然後他就會幫你自動產生莫名其妙的欄位像「user_user_id」
舉個例子,一個User可以有很多篇文章
User的模型長這樣:
[Key]
public string user_id { get; set; }
public string user_account { get; set; }
public string user_password { get; set; }
public virtual ICollection<post> post { get; set; }

Post的模型
[Key]
public string post_id{ get; set; }
public string user_id { get; set; }
public string post_title { get; set; }
public virtual users users { get; set; }
簡短表達一下就好(´・ω・`)
我自己的習慣是外來鍵會用跟原表相同的ID,但是在EF的規則裡面virtual users應該用對應的外來鍵「user_id」命名  ((沒實際嘗試,沒理解錯文章的話是這樣
可是規則上「變數名稱」需要和「資料庫欄位名稱」相同,所以不太可能把string user_id改成其他名稱
所以要在「users」Model 的 post 上面新增外鍵屬性,資料才能正確締結

修改後會長這樣
[Key]
public string user_id { get; set; }
public string user_account { get; set; }
public string user_password { get; set; }
[ForeignKey("user_id")]
public virtual ICollection<post> post { get; set; }
屬性中填的字串是「user」這個 Model 要連到「post」的外鍵變數名稱
假設「user」的Key只有id,那屬性中的字串就是打id而非「post」中的user_id
然後 post 不需要去更動
不是很難處理的問題,但那個詭異的「user_user_id」讓我找原因找很久....
我一直在確認我哪裡輸錯變數了跟資料庫沒有動到,這個關鍵字又太廣泛了

SqlNullValueException

這個問題就簡單很多了,在可能為空值的資料上記得加個?就好
像是可能文章標籤可以為空
[Key]
public string post_id{ get; set; }
public string user_id { get; set; }
public string post_title { get; set; }
public string? post_tag { get; set; }
public virtual users users { get; set; }
這樣就行惹
也是不會第一時間反應過來的問題,一度以為是資料庫連失敗沒抓到資料產生的錯誤QQ
-
我直接把我出錯的關鍵字放出來了,希望可以幫到路過的朋友 :3

創作回應

相關創作

更多創作