首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

自製 ORM 框架核心:BindFieldAttribute 特性定義與欄位對應設定 (第 11 講上第 5 部分)

     編輯:關於C語言

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。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved