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

企業級 ASP.NET 2.0 資料存取層實作:以 AdventureWorks 為例

     編輯:關於ASP.NET

本文示範如何建立獨立的資料存取層 (DAL) 類別庫專案,使用 Microsoft Enterprise Library Data Access Application Block 封裝 ADO.NET,實作 ProductCategoryDB 類別透過預存程序取得產品分類,並搭配 DataAccessHelper 將 IDataReader 映射至領域實體 ProductCategory,展現分層架構、相依性反轉與可測試性的最佳實踐。

專案結構

  • AdventureWorksTraderEntities:領域實體 (POCO),如 ProductCategory。
  • AdventureWorksTraderDataAccess:DAL 實作,參考 EntLib Microsoft.Practices.EnterpriseLibrary.Data。
  • AdventureWorksTraderBusiness:BLL 協調 DAL,執行業務規則 (未在本文展示)。
  • Web/UI:呼叫 BLL,不直接參考 DAL。

ProductCategoryDB 核心程式碼

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using AdventureWorksTraderEntities;

namespace AdventureWorksTraderDataAccess
{
    public class ProductCategoryDB
    {
        // 欄位映射:資料庫欄位 → 實體屬性
        private readonly DataColumnMapping[] _mappings = new[]
        {
            new DataColumnMapping("ProductCategoryID", "ProductCategoryID"),
            new DataColumnMapping("Name", "Name"),
            new DataColumnMapping("rowguid", "Rowguid"),
            new DataColumnMapping("ModifiedDate", "ModifiedDate")
        };

        public IList GetProductCategories()
        {
            var list = new List();
            Database db = DatabaseFactory.CreateDatabase(); // 讀取 web.config 連線字串
            const string spName = "GetProductCategories";

            using (DbCommand cmd = db.GetStoredProcCommand(spName))
            using (IDataReader reader = db.ExecuteReader(cmd))
            {
                while (reader.Read())
                {
                    var temp = new ProductCategory();
                    // 利用 Helper 將 Reader 映射至實體
                    ProductCategory category = (ProductCategory)DataAccessHelper.PopulateEntity(temp, _mappings, reader);
                    list.Add(category);
                }
            }
            return list;
        }
    }
}

關鍵設計亮點

原則體現方式
分層隔離DAL 僅回傳實體,不含 UI 邏輯;UI 僅依賴 BLL 介面。
相依性反轉高層 (BLL) 定義介面,低層 (DAL) 實作;可替換為 Mock DAL 單元測試。
Enterprise Library統一連線管理、參數化指令、交易支援、設定驅動 (連線字串在 config)。
映射分離DataColumnMapping 陣列集中維護欄位對應,Schema 變更只改一處。
資源釋放using 區塊確保 IDataReader、DbCommand 正確 Dispose。

DataAccessHelper.PopulateEntity 簡易實作概念

public static object PopulateEntity(object entity, DataColumnMapping[] mappings, IDataReader reader)
{
    foreach (var map in mappings)
    {
        int ordinal = reader.GetOrdinal(map.DataSetColumnName); // 資料庫欄位
        if (!reader.IsDBNull(ordinal))
        {
            PropertyInfo prop = entity.GetType().GetProperty(map.PropertyName);
            if (prop != null && prop.CanWrite)
            {
                object value = reader.GetValue(ordinal);
                prop.SetValue(entity, Convert.ChangeType(value, prop.PropertyType), null);
            }
        }
    }
    return entity;
}

擴展建議

  • 導入 Dapper 或 Entity Framework Core 替代手寫映射,提升開發效率。
  • 建立 IProductCategoryRepository 介面,DAL 實作介面,BLL 注入介面,徹底解耦。
  • 加入快取策略:MemoryCache 或 Redis 快取熱門分類資料。
  • 實作 UnitOfWork 模式管理跨 Repository 交易。

結語

雖然技術棧已演進,但「分層、介面導向、設定驅動、資源安全」的 DAL 設計原則永不過時。本範例展示了在 ADO.NET + EntLib 時代如何落地這些原則,為現代 ORM 架構鋪路。

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