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

C# Attribute特性應用實戰(二):自定義Table/Column特性構建OR映射元數據模型

     編輯:關於C語言

特性也是類:構造函數重載與屬性賦值

附加特性時可使用構造函數參數**或屬性名=值**語法:


[Table("UserInfo")]
public class UserInfo
{
    private int _userId;
    [Column("UserId", DbType.Int32)]
    public int UserId { get => _userId; set => _userId = value; }
    
    private string _userName;
    [Column("UserName", DbType.String)] // 注意:原文缺少引號,此處修正
    public string UserName { get => _userName; set => _userName = value; }
}

ColumnAttribute完整定義


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

TableAttribute定義


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

設計要點

  • AttributeUsage精確限定作用目標(類/屬性),防止誤用。
  • 提供多構造函數重載,支援[Column("Name")]與[Column("Name", DbType.Int32)]雙語法。
  • 屬性ColumnName默認null,運行時回退屬性名,靈活適配命名一致場景。
  • DbType使用System.Data.DbType枚舉,與ADO.NET參數類型體系對齊。

元數據模型完整性

至此擁有:

  1. 類級TableAttribute → 表名
  2. 屬性級ColumnAttribute → 列名、數據類型

配合反射讀取(下篇),即可構建完整OR映射元數據驅動引擎雛形。

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