本文示範如何建立獨立的資料存取層 (DAL) 類別庫專案,使用 Microsoft Enterprise Library Data Access Application Block 封裝 ADO.NET,實作 ProductCategoryDB 類別透過預存程序取得產品分類,並搭配 DataAccessHelper 將 IDataReader 映射至領域實體 ProductCategory,展現分層架構、相依性反轉與可測試性的最佳實踐。
ProductCategory。Microsoft.Practices.EnterpriseLibrary.Data。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。 |
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;
}
IProductCategoryRepository 介面,DAL 實作介面,BLL 注入介面,徹底解耦。MemoryCache 或 Redis 快取熱門分類資料。UnitOfWork 模式管理跨 Repository 交易。雖然技術棧已演進,但「分層、介面導向、設定驅動、資源安全」的 DAL 設計原則永不過時。本範例展示了在 ADO.NET + EntLib 時代如何落地這些原則,為現代 ORM 架構鋪路。