BindFieldAttribute 完整原始碼
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class BindFieldAttribute : Attribute
{
public BindFieldAttribute() { }
public BindFieldAttribute(string name) { strName = name; }
private string strName = null;
public string Name { get { return strName; } }
private bool bolKey = false;
public bool Key { get { return bolKey; } set { bolKey = value; } }
private string strReadFormat = null;
public string ReadFormat { get { return strReadFormat; } set { strReadFormat = value; } }
private string strWriteFormat = null;
public string WriteFormat { get { return strWriteFormat; } set { strWriteFormat = value; } }
}
屬性用途說明
| 屬性 | 用途 |
Name | 對應資料庫欄位名稱;若為空則預設使用屬性名稱。 |
Key | 標記為關鍵欄位 (主鍵),用於 UPDATE/DELETE 的 WHERE 條件產生。 |
ReadFormat | 從資料庫讀取時的格式化解析字串 (如 yyyyMMdd 解析日期)。 |
WriteFormat | 寫入資料庫時的格式化字串 (如日期輸出 yyyy-MM-dd)。 |
應用範例
[BindField("EmployeeID", Key = true)]
public int EmployeeID { get; set; }
[BindField("BirthDate", ReadFormat = "yyyyMMdd", WriteFormat = "yyyy-MM-dd")]
public DateTime BirthDate { get; set; }
設計重點
AttributeUsage 限定只能套用於 Property,避免誤用。
- 格式化屬性支援
IFormattable 型別 (DateTime、數值) 的雙向轉換。
- 關鍵欄位標記讓框架自動組裝 WHERE 子句,減少手寫 SQL。