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

C# Attribute 實戰應用:打造輕量級 ORM 映射框架

     編輯:關於C#

Attribute(特性)是 C# 中為程式碼元素附加中繼資料的強大機制。本文示範如何利用自訂 Attribute 實現物件關係映射(ORM)的核心功能,將類別對應資料表、屬性對應欄位。

Attribute 基本運作原理

編譯器偵測到 Attribute 時,會在名稱後附加 Attribute 後綴(若原名已含則不加),於命名空間搜尋對應類別。所有 Attribute 必須繼承 System.Attribute。

定義 TableAttribute 對應資料表

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class TableAttribute : Attribute {
    private string tableName;
    public string TableName {
        get { return tableName; }
        set { tableName = value; }
    }
    public TableAttribute() { this.tableName = null; }
    public TableAttribute(string tableName) { this.tableName = tableName; }
}

AttributeUsage 限定僅能套用於類別、不可重複、不繼承。

定義 ColumnAttribute 對應欄位

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class ColumnAttribute : Attribute {
    private string columnName;
    private DbType dbType;
    public string ColumnName { get { return columnName; } set { columnName = value; } }
    public DbType DbType { get { return dbType; } set { dbType = value; } }
    public ColumnAttribute() { this.columnName = null; this.dbType = DbType.String; }
    public ColumnAttribute(string columnName) { this.columnName = columnName; }
    public ColumnAttribute(string columnName, DbType dbType) : this(columnName) { this.dbType = dbType; }
}

實體類別標註

[Table("UserInfo")]
public class UserInfo {
    private int userId;
    [Column("UserId", DbType.Int32)]
    public int UserId { get { return userId; } set { userId = value; } }

    private string userName;
    [Column("UserName", DbType.String)]
    public string UserName { get { return userName; } set { userName = value; } }
}

反射讀取中繼資料建構 SQL


UserInfo userInfo = new UserInfo();
Type type = userInfo.GetType();

TableAttribute ta = (TableAttribute)type.GetCustomAttributes(false)[0];
Console.WriteLine("資料表名:" + ta.TableName);

PropertyInfo[] infos = type.GetProperties();
foreach (PropertyInfo info in infos) {
    object[] attributes = info.GetCustomAttributes(false);
    foreach (object att in attributes) {
        if (att is ColumnAttribute) {
            ColumnAttribute ca = att as ColumnAttribute;
            string cn = ca.ColumnName == null ? info.Name : ca.ColumnName;
            Console.WriteLine("欄位名:" + cn);
            Console.WriteLine("欄位型別:" + ca.DbType);
        }
    }
}

ORM 映射執行結果

此模式為 Entity Framework 等成熟 ORM 框架的核心基礎,理解其運作有助於深入掌握框架內部機制。

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