zoukankan      html  css  js  c++  java
  • ASP.NET数据库访问系列教程01概述篇 创建数据访问层(下)

    ASP.NET数据库访问系列教程

    本教程深入探讨了基于ASP.NET 2.0技术的数据库访问方法和模式。这些介绍非常简明,并且提供了一步步的指导和大量的截屏。

    该系列教程包括:

    • 概述篇
    • 基础报表
    • 主/明细报表
    • 自定义格式报表
    • 编辑,插入和删除数据
    • 分页和排序、自定义按钮事件
    • 使用DataList和Repeater控件显示数据
    • 使用DataList和Repeater进行数据筛选
    • 通过DataList编辑和删除数据
    • 使用DataList和Repeater控件进行分页和排序
    • 自定义DataList和Repeater控件的按钮事件
    • 从ASP.NET页面直接访问数据库
    • 扩展GridView控件
    • 操作二进制文件
    • 数据缓存
    • 基于数据库的站点地图
    • 批量数据处理
    • 高级数据库访问操作

    #1 概述篇-创建数据访问层(下)

    本文档是 Visual C# 教程

    该教程从头开始使用 Typed DataSet(强类型 DataSet)创建数据访问层 (DAL),以访问数据库中的信息。

    步骤 5:完成数据访问层

    注意,ProductsTableAdapters 类返回Products 表的 CategoryIDSupplierID 值,但不包含Categories 表的 CategoryName 列,或 Suppliers 表的 CompanyName 列,尽管在显示产品信息时我们可能也希望显示这些列。我们可以扩充TableAdapter 初始方法GetProducts() ,使其包括 CategoryNameCompanyName 列值,这将更新强类型的DataTable ,使其同样包含这些新列。

    但是,这样就会出现一个问题,因为TableAdapter 的添加、更新和删除方法并不是基于这个初始方法。幸运的是,自动生成的添加、更新和删除方法不受SELECT 子句中的子查询影响。通过把对 CategoriesSuppliers 的查询作为子查询添加到我们原来的查询语句中,而不是使用JOIN 连接,我们可以避免重写这些用来修改数据的方法。右键单击ProductsTableAdapter 中的 GetProducts() 方法并选择Configure 。随后将 SELECT 子句修改如下:

    SELECT ProductID, ProductName, SupplierID, CategoryID,
    QuantityPerUnit, UnitPrice, UnitsInStock, UnitsOnOrder, ReorderLevel, Discontinued,
    (
    SELECT CategoryName FROM Categories
    WHERE Categories.CategoryID = Products.CategoryID) as CategoryName,
    (
    SELECT CompanyName FROM Suppliers
    WHERE Suppliers.SupplierID = Products.SupplierID) as SupplierName
    FROM Products


    图29 :GetProducts() 方法更新SELECT 语句


     

    使用这个新查询更新 GetProducts() 方法后,DataTable 将包含下面两个新列:CategoryNameSupplierName

    图30 :Products 数据表有两个新列


     

    花点时间也来更新 GetProductsByCategoryID(categoryID) 方法中的 SELECT 子句。

    如果使用 JOIN 语法更新 GetProducts() 中的 SELECT ,DataSet 设计器将不能使用数据库直接模式自动生成数据插入、更新和删除的方法。您不得不手动的生成这些方法,就好象在本教程早先时候我们对InsertProduct 方法的做法一样。另外,如果您希望使用批量更新模式,就必须手动提供InsertCommandUpdateCommandDeleteCommand 属性值。


     

    添加剩余的TableAdapters

    至今为止,我们只是介绍了单个数据库表的单个TableAdapter 。但是,Northwind 数据库包含需要我们在我们的 Web 应用程序中操作的几个相关表。一个 Typed DataSet 可以包含多个相关的 DataTable 。因此,要完成我们的 DAL ,还需要为我们在这些教程中用到的其它表添加DataTable 。要添加新的 TableAdapter 到 Typed DataSet ,打开 DataSet Designer ,右键单击Designer 并选择 Add / TableAdapter 。这将创建一个新的 DataTable 和 TableAdapter ,并引导你完成我们在前面教程所讨论的配置向导。

    花几分钟的时间,用下面的查询语句创建对应的TableAdapters 及其方法。注意,ProductsTableAdapter 中的查询包括子查询,以获取每个产品的类别和供应商名称这些信息。另外,如果您一直都在跟着教程操作,那您就已经添加了ProductsTableAdapter 类的 GetProducts()GetProductsByCategoryID(categoryID) 方法。


     

    • ProductsTableAdapter
      • GetProducts:
        SELECT ProductID, ProductName, SupplierID,
        CategoryID, QuantityPerUnit, UnitPrice, UnitsInStock,
        UnitsOnOrder, ReorderLevel, Discontinued,
        (SELECT CategoryName FROM Categories WHERE
        Categories.CategoryID = Products.CategoryID) as
        CategoryName, (SELECT CompanyName FROM Suppliers
        WHERE Suppliers.SupplierID = Products.SupplierID)
        as SupplierName
        FROM Products
      • GetProductsByCategoryID:
        SELECT ProductID, ProductName, SupplierID, CategoryID,
        QuantityPerUnit, UnitPrice, UnitsInStock, UnitsOnOrder,
        ReorderLevel, Discontinued, (SELECT CategoryName
        FROM Categories WHERE Categories.CategoryID =
        Products.CategoryID) as CategoryName,
        (SELECT CompanyName FROM Suppliers WHERE
        Suppliers.SupplierID = Products.SupplierID)
        as SupplierName
        FROM Products
        WHERE CategoryID = @CategoryID
      • GetProductsBySupplierID:
        SELECT ProductID, ProductName, SupplierID, CategoryID,
        QuantityPerUnit, UnitPrice, UnitsInStock, UnitsOnOrder,
        ReorderLevel, Discontinued, (SELECT CategoryName
        FROM Categories WHERE Categories.CategoryID =
        Products.CategoryID) as CategoryName,
        (SELECT CompanyName FROM Suppliers WHERE
        Suppliers.SupplierID = Products.SupplierID) as SupplierName
        FROM Products
        WHERE SupplierID = @SupplierID
      • GetProductByProductID:
        SELECT ProductID, ProductName, SupplierID, CategoryID,
        QuantityPerUnit, UnitPrice, UnitsInStock, UnitsOnOrder,
        ReorderLevel, Discontinued, (SELECT CategoryName
        FROM Categories WHERE Categories.CategoryID =
        Products.CategoryID) as CategoryName,
        (SELECT CompanyName FROM Suppliers WHERE Suppliers.SupplierID = Products.SupplierID)
        as SupplierName
        FROM Products
        WHERE ProductID = @ProductID
    • CategoriesTableAdapter
      • GetCategories:
        SELECT CategoryID, CategoryName, Description
        FROM Categories
      • GetCategoryByCategoryID:
        SELECT CategoryID, CategoryName, Description
        FROM Categories
        WHERE CategoryID = @CategoryID
    • SuppliersTableAdapter
      • GetSuppliers:
        SELECT SupplierID, CompanyName, Address,
        City, Country, Phone
        FROM Suppliers
      • GetSuppliersByCountry:
        SELECT SupplierID, CompanyName, Address,
        City, Country, Phone
        FROM Suppliers
        WHERE Country = @Country
      • GetSupplierBySupplierID:
        SELECT SupplierID, CompanyName, Address,
        City, Country, Phone
        FROM Suppliers
        WHERE SupplierID = @SupplierID
    • EmployeesTableAdapter
      • GetEmployees:
        SELECT EmployeeID, LastName, FirstName, Title,
        HireDate, ReportsTo, Country
        FROM Employees
      • GetEmployeesByManager:
        SELECT EmployeeID, LastName, FirstName, Title,
        HireDate, ReportsTo, Country
        FROM Employees
        WHERE ReportsTo = @ManagerID
      • GetEmployeeByEmployeeID:
        SELECT EmployeeID, LastName, FirstName, Title,
        HireDate, ReportsTo, Country
        FROM Employees
        WHERE EmployeeID = @EmployeeID

    图31 :添加了四个TableAdapter 的 DataSet 设计器


     

    向 DAL 添加自定义代码

    添加到 Typed DataSet 的TableAdapter 和 DataTable 由 XML Schema Definition 文件 (Northwind.xsd) 来描述。通过右键单击 Solution Explorer 中的Northwind.xsd 文件并选择View Code ,可以查看该 schema 的信息。

    图32 :针对Northwinds Typed DataSet 的 XML Schema Definition (XSD) 文件

    编译或运行时(如果需要),该schema 信息在设计时被译成 C# 或 Visual Basic 代码,此时您可以使用调试器进行调试。要查看这个自动生成的代码,转入Class View 并找到TableAdapter 或 Typed DataSet 类。如果在屏幕上看不到 Class View ,转入View 菜单并选中它,或按下 Ctrl+Shift+C 。从 Class View 上可以看到 Typed DataSet 和TableAdapter 类的属性、方法和事件。要查看某个方法的代码,双击Class View 中该方法的名称或右键单击它并选择 Go To Definition 。

    图33 : 通过选择Class View 的 Selecting Go To Definition 检查自动生成的代码


    尽管自动生成的代码可以节省很多时间,但是它们通常都是通用代码,需要自定义来满足应用程序的特定要求。可是,拓展自动生成代码的风险在于生成代码的工具可以决定何时“再生成”而覆盖了您的自定义操作。有了.NET 2.0 的新的部分类概念,我们可以非常简单的将一个类的定义分写在几个文件中。这样我们能够添加自己的方法、属性和事件到自动生成的类,而不必担心Visual Studio 覆盖了我们的自定义内容。

    为了说明如何自定义 DAL ,我们现在把GetProducts() 方法添加到SuppliersRow 类。SuppliersRow 类在Suppliers 表呈现一条记录;每个供应商可以提供零到多个产品,这样GetProducts() 将返回指定供应商的那些产品信息。要做到这些,需要在App_Code 文件夹中创建一个名为 SuppliersRow.cs 的新的类文件,然后在其中添加下列代码:

    1 using System;
    2 using System.Data;
    3 using NorthwindTableAdapters;
    4
    5 public partial class Northwind
    6 {
    7 public partial class SuppliersRow
    8 {
    9 public Northwind.ProductsDataTable GetProducts()
    10 {
    11 ProductsTableAdapter productsAdapter =
    12 new ProductsTableAdapter();
    13 return
    14 productsAdapter.GetProductsBySupplierID(this.SupplierID);
    15 }
    16 }
    17 }



    该部分类指示编译器创建 Northwind.SuppliersRow 类时包含我们刚定义的 GetProducts() 方法。如果您 build 您的项目,然后返回到 Class View ,将看见GetProducts() 现在被列为Northwind.SuppliersRow 的方法。

    图34 G:GetProducts() 方法现在是Northwind.SuppliersRow 类的一部分

    GetProducts() 方法现在可用来列举某供应商的全套产品,如下面的代码所示:

    1 NorthwindTableAdapters.SuppliersTableAdapter suppliersAdapter =
    2 new NorthwindTableAdapters.SuppliersTableAdapter();
    3
    4 // Get all of the suppliers
    5 Northwind.SuppliersDataTable suppliers =
    6 suppliersAdapter.GetSuppliers();
    7
    8 // Enumerate the suppliers
    9 foreach (Northwind.SuppliersRow supplier in suppliers)
    10 {
    11 Response.Write("Supplier: " + supplier.CompanyName);
    12 Response.Write("<ul>");
    13
    14 // List the products for this supplier
    15 Northwind.ProductsDataTable products = supplier.GetProducts();
    16 foreach (Northwind.ProductsRow product in products)
    17 Response.Write("<li>" + product.ProductName + "</li>");
    18
    19 Response.Write("</ul><p> </p>");
    20 }


     

    该数据也可以在任何 ASP.NET 的Web 数据控件中显示。以下页面使用了具有两个字段的GridView 控件:

    • 显示每个供应商名称的 BoundField 和
    • 一个 TemplateField ,它包含了一个 BulletedList 控件,该控件与每个供应商的 GetProducts() 方法的返回结果绑定。

    我们会在后面的教程中探讨如何显示这种主/ 明细报表。就目前而言,该示例旨在说明添加到Northwind.SuppliersRow 类的自定义方法的使用。

    SuppliersAndProducts.aspx

    1 <%@ Page Language="C#" CodeFile="SuppliersAndProducts.aspx.cs"
    2 AutoEventWireup="true" Inherits="SuppliersAndProducts" %>
    3
    4 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    5 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    6
    7 <html xmlns="http://www.w3.org/1999/xhtml" >
    8 <head runat="server">
    9 <title>Untitled Page</title>
    10 <link href="Styles.css" rel="stylesheet" type="text/css" />
    11 </head>
    12 <body>
    13 <form id="form1" runat="server">
    14 <div>
    15 <h2>
    16 Suppliers and Their Products</h2>
    17 <p>
    18 <asp:GridView ID="GridView1" runat="server"
    19 AutoGenerateColumns="False"
    20 CssClass="DataWebControlStyle">
    21 <HeaderStyle CssClass="HeaderStyle" />
    22 <AlternatingRowStyle CssClass="AlternatingRowStyle" />
    23 <Columns>
    24 <asp:BoundField DataField="CompanyName"
    25 HeaderText="Supplier" />
    26 <asp:TemplateField HeaderText="Products">
    27 <ItemTemplate>
    28 <asp:BulletedList ID="BulletedList1"
    29 runat="server"
    30        DataSource="<%# ((Northwind.SuppliersRow) ((System.Data.DataRowView) Container.DataItem).Row).GetProducts() %>"
    31 DataTextField="ProductName">
    32 </asp:BulletedList>
    33 </ItemTemplate>
    34 </asp:TemplateField>
    35 </Columns>
    36 </asp:GridView>
    37 </p>
    38
    39 </div>
    40 </form>
    41 </body>
    42 </html>



    SuppliersAndProducts.aspx.cs

    1 using System;
    2 using System.Data;
    3 using System.Configuration;
    4 using System.Collections;
    5 using System.Web;
    6 using System.Web.Security;
    7 using System.Web.UI;
    8 using System.Web.UI.WebControls;
    9 using System.Web.UI.WebControls.WebParts;
    10 using System.Web.UI.HtmlControls;
    11 using NorthwindTableAdapters;
    12
    13 public partial class SuppliersAndProducts : System.Web.UI.Page
    14 {
    15 protected void Page_Load(object sender, EventArgs e)
    16 {
    17 SuppliersTableAdapter suppliersAdapter = new
    18 SuppliersTableAdapter();
    19 GridView1.DataSource = suppliersAdapter.GetSuppliers();
    20 GridView1.DataBind();
    21 }
    22 }


    图35 :供应商的公司名列在左列,他们的产品在右列

    小结

    创建DAL 应该是开发一个Web 应用程序的第一步,这要在开始创建您的表示层之前进行。通过Visual Studio ,创建一个基于Typed DataSet 的DAL 就成为一项不需要编写一行代码,在10 到15 分钟内就可以完成的任务。教程后面的内容仍旧围绕DAL 进行。 下一教程 我们将定义几个业务规则并看看如何在单个业务逻辑层中实现它们。

    快乐编程!



     

  • 相关阅读:
    Jquery停止动画
    Jquery自定义动画与动画队列
    关系型数据库的常用概念
    三大范式审核
    数据库设计基本步骤
    'NoneType' object is not iterable
    三行神奇的代码
    url的解码方式
    [转]获取当前执行主脚本的方法
    非黑即白--谷歌OCR光学字符识别
  • 原文地址:https://www.cnblogs.com/MingDe/p/2079629.html
Copyright © 2011-2022 走看看