ASP.NET 2.0实现数据访问层2011-11-211. 实现数据访问层本节将讲解数据访问层的实现,该层包括与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;}}}