萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

.NET 自訂屬性實戰:建立資料表/欄位對應映射框架

前言

.NET 屬性提供中繼資料標註能力,配合反射可建構強大的對應映射機制。本文示範如何定義 TableAttribute、FieldAttribute,並建立基底實體類別自動解析屬性,奠定簡易 ORM 雛形。

一、定義類別層級屬性:TableAttribute

[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
public sealed class TableAttribute : Attribute
{
    private readonly string _tableName;
    public TableAttribute(string tableName) => _tableName = tableName;
    public string TableName => _tableName;
}

二、定義屬性層級屬性:FieldAttribute

[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
public class FieldAttribute : Attribute
{
    private readonly string _fieldName;
    private readonly DbType _dbType;
    
    public FieldAttribute(string fieldName) : this(fieldName, DbType.String) { }
    public FieldAttribute(string fieldName, DbType type)
    {
        _fieldName = fieldName;
        _dbType = type;
    }
    public string FieldName => _fieldName;
    public DbType Type => _dbType;
    // 運行期動態賦值用
    public object FieldValue { get; set; }
}

三、建立基底實體類別:BaseEntity

public abstract class BaseEntity
{
    /// 取得資料表名稱
    public string GetTableName()
    {
        var type = this.GetType();
        var attrs = type.GetCustomAttributes(typeof(TableAttribute), true);
        if (attrs.Length == 0)
            throw new InvalidOperationException($"實體類別 {type.Name} 缺少 TableAttribute");
        return ((TableAttribute)attrs[0]).TableName;
    }

    /// 取得屬性對應的 FieldAttribute(含目前值)
    public FieldAttribute GetFieldAttribute(string propertyName)
    {
        var prop = this.GetType().GetProperty(propertyName);
        if (prop == null)
            throw new ArgumentException($"屬性 {propertyName} 不存在");
        
        var attrs = prop.GetCustomAttributes(typeof(FieldAttribute), true);
        if (attrs.Length == 0)
            throw new InvalidOperationException($"屬性 {propertyName} 缺少 FieldAttribute");
        
        var fa = (FieldAttribute)attrs[0];
        fa.FieldValue = prop.GetValue(this);
        return fa;
    }

    /// 取得所有欄位屬性集合
    public IEnumerable GetAllFieldAttributes()
    {
        foreach (var prop in this.GetType().GetProperties())
        {
            var attrs = prop.GetCustomAttributes(typeof(FieldAttribute), true);
            if (attrs.Length > 0)
            {
                var fa = (FieldAttribute)attrs[0];
                fa.FieldValue = prop.GetValue(this);
                yield return fa;
            }
        }
    }
}

四、實際使用範例

[Table("Products")]
public class Product : BaseEntity
{
    [Field("ProductID", DbType.Int32)]
    public int Id { get; set; }

    [Field("ProductName", DbType.String)]
    public string Name { get; set; }

    [Field("UnitPrice", DbType.Decimal)]
    public decimal Price { get; set; }

    [Field("Discontinued", DbType.Boolean)]
    public bool IsDiscontinued { get; set; }
}

// 使用
var p = new Product { Id = 1, Name = "筆記型電腦", Price = 25000, IsDiscontinued = false };
Console.WriteLine($"Table: {p.GetTableName()}"); // Products
foreach (var f in p.GetAllFieldAttributes())
{
    Console.WriteLine($"{f.FieldName} ({f.Type}) = {f.FieldValue}");
}

五、擴充應用:動態建構 SQL

public static class SqlBuilder
{
    public static (string Sql, object[] Parameters) BuildInsert(BaseEntity entity)
    {
        var fields = entity.GetAllFieldAttributes().ToList();
        var columns = string.Join(", ", fields.Select(f => f.FieldName));
        var params_ = string.Join(", ", fields.Select((f, i) => $"@p{i}"));
        var sql = $"INSERT INTO {entity.GetTableName()} ({columns}) VALUES ({params_})";
        var parameters = fields.Select(f => f.FieldValue).ToArray();
        return (sql, parameters);
    }
}

六、進階提示

  • 快取反射結果:使用 ConcurrentDictionary<Type, MetaInfo> 快取屬性資訊,避免重複反射開銷。
  • 支援唯讀/忽略欄位:擴充 FieldAttribute 加入 IsReadOnly、IsIgnore 旗標。
  • 對應 Dapper/ADO.NET:產出的 SQL 與參數可直接餵給 connection.Execute(sql, parameters)。
  • 來源產生器:.NET 6+ 可用 Source Generator 編譯期產生映射程式碼,完全移除反射開銷。

結語

自訂屬性配合反射,能以極少代碼建立類型安全的對應映射層。這是理解 ORM 內部運作的最佳切入點,也能在輕量專案中直接落地使用。現代開發建議搭配快取與來源產生器進一步提升效能。

copyright © 萬盛學電腦網 all rights reserved