1. 實現數據訪問層
本節將講解數據訪問層的實現,該層包括與AdventureWorks數據庫通信的所有必要類和方法。首先,使用Visual Studio 2005創建新的Visual C#類庫項目AdventureWorksTraderDataAccess。當這個項目創建後,可修改默認類名稱為ProductCategoryDB。示例1說明了ProductCategoryDB類的實現代碼。
示例1:實現ProductCategoryDB類
using System; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Collections.Generic; using System.Text; using AdventureWorksTraderEntities; using Microsoft.Practices.EnterpriseLibrary.Data; namespace AdventureWorksTraderDataAccess { public class ProductCategoryDB { private DataColumnMapping[] mappings = new DataColumnMapping[] { new DataColumnMapping("ProductCategoryID", "ProductCategoryID"), new DataColumnMapping("Name", "Name"), new DataColumnMapping("rowguid", "Rowguid"), new DataColumnMapping("ModifiedDate", "ModifiedDate") }; public IList〈ProductCategory> GetProductCategories() { IList〈ProductCategory> list = new List〈ProductCategory>(); Database db = DatabaseFactory.CreateDatabase(); string storedProcedureName = "GetProductCategories"; DbCommand dbCommand = db.GetStoredProcCommand(storedProcedureName); using (IDataReader reader = db.ExecuteReader(dbCommand)) { while (reader.Read()) { ProductCategory temp = new ProductCategory(); ProductCategory category = (ProductCategory)DataAccessHelper.PopulateEntity(temp, mappings, reader); list.Add(category); } } return list; } } }