附加特性時可使用構造函數參數**或屬性名=值**語法:
[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; }
}
[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; }
}
[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參數類型體系對齊。至此擁有:
TableAttribute → 表名ColumnAttribute → 列名、數據類型配合反射讀取(下篇),即可構建完整OR映射元數據驅動引擎雛形。