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

構建屬於自己的 MiniORM 框架 (一):反射與 Attribute 在 ORM 映射中的應用

     編輯:關於C#

本系列首篇,奠基 MiniORM 實現基石:反射 與 自定義 Attribute 的結合,實現運行時動態獲取對象-數據庫映射規則。

反射 基礎

反射允許運行時動態獲取類型信息 (屬性、方法、特性等) 並動態調用/賦值。

public class Person {
    public string Name { get; set; }
    public int Age { get; set; }
    public string Sex { get; set; }
}

// 運行時獲取屬性值
Person p = new Person { Name = "snoopy", Age = 5, Sex = "male" };
PropertyInfo[] props = p.GetType().GetProperties();
foreach (var prop in props) {
    Console.WriteLine($"{prop.Name}: {prop.GetValue(p, null)}");
}

// 運行時設置屬性值
foreach (var prop in props) {
    if (prop.Name == "Name") prop.SetValue(p, "Hellokitty", null);
}

反射輸出結果

自定義 Attribute 定義映射規則

Attribute 是運行時掛載在程式元素 (類、屬性、方法) 上的元數據類,必須繼承 System.Attribute。

public class DataFieldAttribute : Attribute {
    public string FieldName { get; set; } // 數據庫列名
    public string FieldType { get; set; } // 數據庫類型
    public DataFieldAttribute(string fieldName, string fieldType) { ... }
}

應用 Attribute 描述映射

public class Person {
    [DataFieldAttribute("name", "nvarchar")] public string Name { get; set; }
    [DataFieldAttribute("age", "int")] public int Age { get; set; }
    [DataFieldAttribute("sex", "nvarchar")] public string Sex { get; set; }
}

反射 + Attribute:動態獲取映射字典

Person p = new Person { Name = "snoopy", Age = 5, Sex = "male" };
PropertyInfo[] props = p.GetType().GetProperties();
foreach (var prop in props) {
    object[] attrs = prop.GetCustomAttributes(typeof(DataFieldAttribute), false);
    if (attrs.Length > 0) {
        var dfa = (DataFieldAttribute)attrs[0];
        Console.WriteLine($"{prop.Name} -> DB Column: {dfa.FieldName} ({dfa.FieldType})");
    }
}

映射輸出

待解決問題 (下篇將展開)

  1. 實體類對應哪張表? (DataObjectAttribute)
  2. 主鍵 (PK) / 外鍵 (FK) 如何標記?
  3. 自增列 (Identity) 如何識別?
  4. 關聯對象 (組合/聚合) 如何映射?
  5. 唯一性約束如何表達?
  6. 事務如何管理?

掌握「反射獲取元數據 + Attribute 定義規則」這一核心模式,即可構建輕量級 ORM 框架雛形。

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