萬盛學電腦網

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

C# 反射簡化資料庫實體映射:DataTable 自動賦值實體屬性

應用場景

資料庫查詢回傳 `DataTable`,欄位名與實體類別屬性名一致 (或有固定前綴映射)。傳統手動 `entity.Field = row["Field"]` 程式碼冗長、易出錯、維護困難。利用**反射**實現自動映射,大幅減少樣板碼。

實體類別定義 (對應資料表欄位)

namespace MyApp.Models
{
    public class FieldRuleInfo
    {
        // 欄位名稱對應資料庫欄位 (加前綴 gStr 區分)
        public string gStrFNo { get; set; }
        public string gStrFName { get; set; }
        public string gStrFLock { get; set; }
        public string gStrFCaption { get; set; }
        public string gStrFType { get; set; }
        public string gStrFMust { get; set; }
        public string gStrFMin { get; set; }
        public string gStrFMax { get; set; }
        public string gStrFDefault { get; set; }
        public string gStrFDate { get; set; }
        public string gStrFDB { get; set; }
        public string gStrFAllow { get; set; }
        public string gStrFDisallow { get; set; }
        public string gStrFSB { get; set; }
        public string gStrFBig { get; set; }
        public string gStrFSmall { get; set; }
        public string gStrFInputMethod { get; set; }
        public string gStrFCHK { get; set; }
        public string gStrFRelation { get; set; }
        public string gStrFDesc { get; set; }
        public string gStrFSecond { get; set; }
        public string gStrFQC { get; set; }
        public string gStrFException { get; set; }
        public string gStrFASupp { get; set; }
        public string gStrFYQH { get; set; }
        public string gStrFPos { get; set; }
        public string gStrFStar { get; set; }
        public string gStrFSave { get; set; }
        public string gStrFAddress { get; set; }
        public string gStrFLblColor { get; set; }
        public string gStrFIsCheckList { get; set; }
    }
}

核心映射邏輯:反射自動賦值

using System;
using System.Data;
using System.Reflection;
using System.Collections.Generic;

public class FieldRuleRepository
{
    private List _fieldRules = new List();
    
    public bool LoadFieldRules(int formType, int region)
    {
        string sql = BuildSql(formType, region); // 依業務邏輯組裝 SQL
        DataTable dt = DbHelper.GetDataTable(sql); // 你的資料存取封裝
        
        if (dt.Rows.Count == 0) return false;
        
        // 1. 取得實體類型資訊 (緩存可優化)
        Type entityType = typeof(FieldRuleInfo);
        
        // 2. 遍歷 DataTable 每一行
        foreach (DataRow row in dt.Rows)
        {
            // 建立實體實例
            var entity = new FieldRuleInfo();
            
            // 3. 遍歷 DataTable 每一欄,反射映射到實體屬性
            foreach (DataColumn col in dt.Columns)
            {
                // 映射規則:資料庫欄位名 -> 實體屬性名 (加前綴 "gStr")
                string propName = "gStr" + col.ColumnName;
                
                // 取得 PropertyInfo (區分大小寫、公開/非公開、實例/靜態)
                PropertyInfo prop = entityType.GetProperty(propName, 
                    BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                
                if (prop != null && prop.CanWrite)
                {
                    // 安全取值:處理 DBNull
                    object value = row[col];
                    if (value == DBNull.Value) value = null;
                    
                    // 型別轉換 (這裡假設皆為 string,實務可擴充型別轉換器)
                    prop.SetValue(entity, value?.ToString(), null);
                }
                // 若找不到屬性,可選擇忽略或記錄警告
            }
            
            _fieldRules.Add(entity);
        }
        
        return true;
    }
    
    public List GetFieldRules() => _fieldRules;
}

關鍵技術點解析

技術點說明
Type.GetType / typeof取得型別中繼資料,`typeof(FieldRuleInfo)` 編譯期安全
GetProperty(name, BindingFlags)依名稱取得屬性資訊,BindingFlags 控制搜尋範圍
PropertyInfo.SetValue(obj, value, index)動態設定屬性值,index 為索引器參數 (屬性無索引器則為 null)
DBNull.Value 處理資料庫 NULL 不能直接指派給 string,必須轉為 null 或預設值
命名慣例映射資料庫欄位 `FName` -> 實體屬性 `gStrFName`,可自訂映射字典替代

進階優化:效能與彈性

1. 緩存 PropertyInfo 避免重複反射

static Dictionary _propCache = new Dictionary();

PropertyInfo GetProp(Type t, string name)
{
    if (!_propCache.TryGetValue(name, out var prop))
    {
        prop = t.GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
        if (prop != null) _propCache[name] = prop;
    }
    return prop;
}

2. 通用映射擴充方法 (適用任何實體)

public static class DataMapper
{
    public static List MapToList(this DataTable dt, Func columnToProp = null) 
        where T : new()
    {
        var list = new List();
        var props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        var propDict = props.ToDictionary(p => p.Name, p => p, StringComparer.OrdinalIgnoreCase);
        
        foreach (DataRow row in dt.Rows)
        {
            T entity = new T();
            foreach (DataColumn col in dt.Columns)
            {
                string propName = columnToProp != null ? columnToProp(col.ColumnName) : col.ColumnName;
                if (propDict.TryGetValue(propName, out var prop) && prop.CanWrite)
                {
                    object val = row[col];
                    if (val == DBNull.Value) val = null;
                    // 簡易型別轉換 (可擴充 IConvertible、TypeConverter)
                    if (val != null && val.GetType() != prop.PropertyType)
                        val = Convert.ChangeType(val, prop.PropertyType);
                    prop.SetValue(entity, val);
                }
            }
            list.Add(entity);
        }
        return list;
    }
}

// 使用:自動映射 (欄位名=屬性名)
var rules = dt.MapToList();

// 使用:自訂映射規則 (欄位 FName -> 屬性 gStrFName)
var rules2 = dt.MapToList(col => "gStr" + col);

3. Dapper / Entity Framework Core 替代方案

新專案強烈建議使用 **Dapper** (輕量、高效、支援映射) 或 **EF Core** (完整 ORM) 取代手寫 ADO.NET + 反射:

// Dapper 範例
using (var conn = new SqlConnection(connStr))
{
    var rules = conn.Query(sql).AsList();
    // 自動處理映射、參數化、連線管理、效能極佳
}

注意事項與最佳實務

  • 效能:反射較慢,熱路徑必須緩存 `PropertyInfo`,或改用 Expression Tree 編譯委託、IL Emit、源碼生成器
  • 型別安全:`Convert.ChangeType` 可能拋出例外,需 try-catch 或自訂轉換器
  • 命名慣例:建立團隊統一命名規範 (如資料庫 snake_case -> C# PascalCase),減少映射配置
  • 唯讀屬性:`CanWrite` 為 false 時跳過 (如唯讀計算屬性)
  • 巢狀物件:單層扁平映射較簡單,複雜物件圖建議用 AutoMapper 或手寫

反射映射是 ADO.NET 時代的經典模式,理解其原理有助於遷移至現代 ORM,並在舊系統維護中優雅解決實體填充問題。

copyright © 萬盛學電腦網 all rights reserved