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

C# 實作自製 ORM(三):自訂 Attribute 定義資料庫欄位映射

     編輯:關於C語言

Attribute 基礎觀念釐清

Attribute(中文常譯「屬性」)與類別 Property(屬性)截然不同。Attribute 是執行期描述程式碼元素(類別、屬性、方法、委派等)的中繼資料,可影響程式行為。常見範例:[STAThread](實為 STAThreadAttribute)、[Serializable]。

自訂 Attribute 僅需繼承 System.Attribute 即可。

定義資料庫欄位對應 Attribute

設計 DataFieldAttribute 標註實體屬性對應的資料表欄位名稱與型別:

public class DataFieldAttribute : Attribute {
    private string _fieldName;
    private string _fieldType;
    public DataFieldAttribute(string fieldName, string fieldType) {
        _fieldName = fieldName; _fieldType = fieldType;
    }
    public string FieldName { get => _fieldName; set => _fieldName = value; }
    public string FieldType { get => _fieldType; set => _fieldType = value; }
}

套用至實體類別

在 Person 類別屬性上標註,建立屬性-欄位一對一對應:

public class Person {
    private string _name; private int _age; private string _sex;
    [DataFieldAttribute("name", "nvarchar")]
    public string Name { get => _name; set => _name = value; }
    [DataFieldAttribute("age", "int")]
    public int Age { get => _age; set => _age = value; }
    [DataFieldAttribute("sex", "nvarchar")]
    public string Sex { get => _sex; set => _sex = value; }
}

此舉完成「類別屬性 ↔ 資料庫欄位」的宣告式映射定義,為後續反射掃描奠基。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved