物件導向程式設計與關聯式資料庫的阻抗失配,是企業級開發的經典難題。類別設計遵循封裝、繼承、多型,而資料表遵循正規化、外鍵約束。Enterprise Library 5.0 內建的映射輔助類別,提供了輕量級的 ORM 解決方案,無需引入 Entity Framework 或 NHibernate 等重型框架即可實現物件關聯映射。
<configSections>
<section name="dataConfiguration"
type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings,
Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0,
Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</configSections>
<dataConfiguration defaultDatabase="sql2005dev" />
<connectionStrings>
<add name="sql2005dev"
connectionString="server=.;database=northwind;uid=sa;pwd=123.com"
providerName="System.Data.SqlClient" />
</connectionStrings>
Database db = DatabaseFactory.CreateDatabase();
// 自動映射所有屬性
IRowMapper<Customer> mapper = MapBuilder<Customer>.BuildAllProperties();
// 建立存儲過程存取器
var accessor = db.CreateSprocAccessor<Customer>("GetAllFromCustomers");
var customers = accessor.Execute();
foreach (var c in customers)
{
Response.Write(c.CompanyName + "<br/>");
}
實作 IParameterMapper 介面,將陣列參數對應至 SQL 參數:
public class ExampleParameterMapper : IParameterMapper
{
public void AssignParameters(DbCommand command, object[] parameterValues)
{
var p1 = command.CreateParameter();
p1.ParameterName = "@p1";
p1.Value = parameterValues[0];
command.Parameters.Add(p1);
var p2 = command.CreateParameter();
p2.ParameterName = "@p2";
p2.Value = parameterValues[1];
command.Parameters.Add(p2);
}
}
// 使用方式
string sql = "SELECT * FROM Customers WHERE CompanyName LIKE @p1 AND ContactName LIKE @p2";
var accessor = db.CreateSqlStringAccessor<Customer>(sql, new ExampleParameterMapper());
var results = accessor.Execute(new string[] { "%stock%", "%s%" });
IRowMapper<T> 介面,完全控制 MapRow 邏輯,支援複雜型別轉換、巢狀物件建構等進階需求。public class Customer
{
public string CustomerID { get; set; }
public string CompanyName { get; set; }
public string ContactName { get; set; }
public string ContactTitle { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string Region { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
public string Phone { get; set; }
public string Fax { get; set; }
}
ExecuteSprocAccessor 系列方法支援多結果集映射Enterprise Library 5.0 的映射工具雖不及完整 ORM 框架功能豐富,但在輕量級專案、維護舊系統、或不願引入重型依賴的場景下,提供了極具性價比的解決方案。其基於慣例的自動映射與可擴充的自訂介面,平衡了開發效率與靈活性。