.NET 屬性提供中繼資料標註能力,配合反射可建構強大的對應映射機制。本文示範如何定義 TableAttribute、FieldAttribute,並建立基底實體類別自動解析屬性,奠定簡易 ORM 雛形。
[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;
}
[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; }
}
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}");
}
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 旗標。connection.Execute(sql, parameters)。自訂屬性配合反射,能以極少代碼建立類型安全的對應映射層。這是理解 ORM 內部運作的最佳切入點,也能在輕量專案中直接落地使用。現代開發建議搭配快取與來源產生器進一步提升效能。