与数据打交道时,一种做法是把跟数据相关的逻辑直接放在表现层中(在一个web应用里,ASP.NET网页构成了表现层)。其形式一般是在ASP.NET 网页的编码部分写ADO.NET 编码或者在标识符部 分使用SqlDataSource控件。在这两种形式里,这种做法都把数据访问逻辑与表现层紧密耦合起来了。但推荐 的做法是,把数据访问逻辑从表现层分离开来。这个分开的层被称作是数据访问层,简写为DAL,一般是通过 一个单独的类库项目来实现的。
跟底层数据源相关的所有编码,譬如建立到数据库的连接,发出SELECT,INSERT ,UPDATE,和DELETE命令等的编码,都应该放置在DAL中。表现层不应该包含对 这些数据访问编码的任何引用,而应该调用DAL中的编码来作所有的数据访问请求。数据访问层包含访问底层数据库数据的方法。譬如,Northwind数据库中,有Products和Categories两个表,它们记录了可供销售的产品以及这些产品 所属的分类。在我们的DAL中,我们将有下面这样的方法:
- GetCategories(), 返回所有分类的信息
- GetProducts(), 返回所有产品的信息
- GetProductsByCategoryID(categoryID), 返回属于指定分类的所有产品的信 息
- GetProductByProductID(productID), 返回指定产品的信息
譬如,DataReader和普通的DataSet是弱类型对象,因为它们的schema是被用来填充它们的数据库查询返回的字段来定义的。要访问弱类型DataTable中的一个特定字段,我们需要用这样的句法:DataTable.Rows[index] ["columnName"]。这个例子中的DataTable的弱类型性质表现在于,我们需要通过一个字符串或序号索引来访问字段名称。而在另一个方面,一个强类型的DataTable,它的所有的字段都是通过属性的形式来实现的 ,访问的编码就会象这样:DataTable.Rows[index].columnName。
C# | |
1
2
3
4
5
6
7
| NorthwindTableAdapters.ProductsTableAdapter
productsAdapter = new
NorthwindTableAdapters.ProductsTableAdapter();
Northwind.ProductsDataTable products;
products = productsAdapter.GetProducts();
foreach (Northwind.ProductsRow productRow in products)
Response.Write("Product: " +
productRow.ProductName + "<br />");
|
ASP.NET | |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
| <%@ Page Language="C#"
AutoEventWireup="true" CodeFile="AllProducts.aspx.cs"
Inherits="AllProducts" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>View All Products in a GridView</title>
<link href="Styles.css"
rel="stylesheet"
type="text/css"
/>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>
All Products</h1>
<p>
<asp:GridView ID="GridView1" runat="server"
CssClass="DataWebControlStyle">
<HeaderStyle CssClass="HeaderStyle" />
<AlternatingRowStyle CssClass="AlternatingRowStyle" />
</asp:GridView>
</p>
</div>
</form>
</body>
</html>
|
AllProducts.aspx.cs
C# | |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using NorthwindTableAdapters;
public partial class
AllProducts : System.Web.UI.Page
{
protected void
Page_Load(object sender, EventArgs e)
{
ProductsTableAdapter productsAdapter = new
ProductsTableAdapter();
GridView1.DataSource = productsAdapter.GetProducts();
GridView1.DataBind();
}
}
|