[翻译]Scott Mitchell 的ASP.NET 2.0数据教程之二:创建一个业务逻辑层

在ASP.NET 2.0中操作数据:创建一个业务逻辑层

英文原版  |   本教程的代码(C#)   |   翻译目录   |   原文目录

导言

本教程的第一节所描述的数据访问层(Data Access Layer,以下简称为DAL)已经清晰地将表示逻辑与数据访问逻辑区分开了。不过,即使DAL将数据访问的细节从表示层中分离出来了,可它却不能处理任何的业务规则。比如说,我们可能不希望产品表中那些被标记为“停用”的产品的“分类编号”“供应商编号”被更新;我们还可能需要应用一些资历规则,比如说我们都不希望被比自己的资历还要浅的人管理。另外一个比较常见的情况就是授权,比如说只有那些具有特殊权限的用户可以删除产品或是更改单价。

我们其实可以将业务逻辑层(Business Logic Layer,以下简称BLL)看作是在数据访问层和表示层之间进行数据交换的桥梁,在这个章节中,我们将讨论一下如何将这些业务规则集成到一个BLL中。需要说明的是,在一个实际的应用程序中,BLL都是以类库(Class Library)的形式来实现的,不过为了简化工程的结构,在本教程中我们将BLL实现为App_Code文件夹中的一系列的类。图一向我们展示了表示层、BLL以及DAL三者之间的结构关系。

aspnet_tutorial02_BusinessLogicLayer_cs_figure01.gif
图一:BLL将表示层与DAL隔开了,并且加入了业务规则

第一步:创建BLL类

我们的BLL4个类组成,每一个BLL类都对应DAL中的一个TableAdapter,它们都从各自的TableAdapter中得到读取、插入、修改以及删除等方法以应用合适的业务规则。

为了更加清晰的区分DALBLL的类,我们在App_Code文件夹中建立两个子文件夹,分别命名为DALBLL。你仅仅需要在解决方案浏览器(Solution Explorer)中右键点击App_Code文件夹,并选择新建文件夹(New Folder),就可以创建新的子文件夹了。建好了这两个文件夹之后,把第一节中所创建的类型化数据集(Typed DataSet)移到DAL文件夹中。

然后,在BLL文件夹中创建4个类文件。同样,你仅仅需要在解决方案浏览器(Solution Explorer)中右键点击BLL文件夹,并选择新建项目(New Item),然后在弹出的对话框中选择类模板(Class template)就可以创建新的类文件了。将这四个文件分别命名为ProductsBLLCategoriesBLLSuppliersBLL以及EmployeesBLL


aspnet_tutorial02_BusinessLogicLayer_cs_figure02.gif
图二:在BLL文件夹中添加4个新的类

接下来,让我们来给这些新建的类加上一些方法,简单的将第一节中的TableAdapter中的那些方法包装起来就行了。现在,这些方法将只能直接使用DAL中的那些方法,我们等会再来给他们加上一些业务逻辑。

注意:如果你使用的是Visual Studio 标准版或以上版本(也就是说,你不是用的Visual Web Developer),那么你还可以使用Class Designer来可视化的设计你的类。你可以在Class Designer Blog上得到关于Visual Studio的这项新功能的详细信息。

ProductsBLL类中,我们一共需要为其添加7个方法:

l         GetProducts() – 返回所有的产品

l         GetProductByProductID(productID) – 返回指定ProductID的产品

l         GetProductsByCategoryID(categoryID) –返回指定分类的产品

l         GetProductsBySupplier(supplierID) –返回指定供应商的产品

l         AddProduct(productName, supplierID, categoryID, quantityPerUnit, unitPrice, unitsInStock, unitsOnOrder, reorderLevel, discontinued) – 向数据库中添加一条产品信息,并返回新添加的产品的ProductID

l         UpdateProduct(productName, supplierID, categoryID, quantityPerUnit, unitPrice, unitsInStock, unitsOnOrder, reorderLevel, discontinued, productID) – 更新一个数据库中已经存在的产品,如果刚好更新了一条记录,则返回true,否则返回false

l         DeleteProduct(productID) – 删除指定ProductID的产品


ContractedBlock.gif ExpandedBlockStart.gif ProductsBLL.cs
  1None.gifusing System;
  2None.gifusing System.Data;
  3None.gifusing System.Configuration;
  4None.gifusing System.Web;
  5None.gifusing System.Web.Security;
  6None.gifusing System.Web.UI;
  7None.gifusing System.Web.UI.WebControls;
  8None.gifusing System.Web.UI.WebControls.WebParts;
  9None.gifusing System.Web.UI.HtmlControls;
 10None.gifusing NorthwindTableAdapters;
 11None.gif
 12None.gif[System.ComponentModel.DataObject]
 13None.gifpublic class ProductsBLL
 14ExpandedBlockStart.gifContractedBlock.gifdot.gif{
 15InBlock.gif    private ProductsTableAdapter _productsAdapter = null;
 16InBlock.gif    protected ProductsTableAdapter Adapter
 17ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 18ExpandedSubBlockStart.gifContractedSubBlock.gif        get dot.gif{
 19InBlock.gif            if (_productsAdapter == null)
 20InBlock.gif                _productsAdapter = new ProductsTableAdapter();
 21InBlock.gif
 22InBlock.gif            return _productsAdapter; 
 23ExpandedSubBlockEnd.gif        }

 24ExpandedSubBlockEnd.gif    }

 25InBlock.gif
 26InBlock.gif
 27InBlock.gif[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
 28InBlock.gif    public Northwind.ProductsDataTable GetProducts()
 29ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{        
 30InBlock.gif        return Adapter.GetProducts();
 31ExpandedSubBlockEnd.gif    }

 32InBlock.gif
 33InBlock.gif    [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, false)]
 34InBlock.gif    public Northwind.ProductsDataTable GetProductByProductID(int productID)
 35ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 36InBlock.gif        return Adapter.GetProductByProductID(productID);
 37ExpandedSubBlockEnd.gif    }

 38InBlock.gif
 39InBlock.gif[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, false)]
 40InBlock.gif    public Northwind.ProductsDataTable GetProductsByCategoryID(int categoryID)
 41ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 42InBlock.gif        return Adapter.GetProductsByCategoryID(categoryID);
 43ExpandedSubBlockEnd.gif    }

 44InBlock.gif
 45InBlock.gif[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, false)]
 46InBlock.gif    public Northwind.ProductsDataTable GetProductsBySupplierID(int supplierID)
 47ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 48InBlock.gif        return Adapter.GetProductsBySupplierID(supplierID);
 49ExpandedSubBlockEnd.gif    }

 50InBlock.gif    [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Insert, true)]
 51InBlock.gif    public bool AddProduct(string productName, int? supplierID, int? categoryID, string quantityPerUnit, 
 52InBlock.gif                          decimal? unitPrice, short? unitsInStock, short? unitsOnOrder, short? reorderLevel, 
 53InBlock.gif                          bool discontinued)
 54ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 55InBlock.gif        // 新建一个ProductRow实例
 56InBlock.gif        Northwind.ProductsDataTable products = new Northwind.ProductsDataTable();
 57InBlock.gif        Northwind.ProductsRow product = products.NewProductsRow();
 58InBlock.gif
 59InBlock.gif        product.ProductName = productName;
 60InBlock.gif        if (supplierID == null) product.SetSupplierIDNull(); else product.SupplierID = supplierID.Value;
 61InBlock.gif        if (categoryID == null) product.SetCategoryIDNull(); else product.CategoryID = categoryID.Value;
 62InBlock.gif        if (quantityPerUnit == null) product.SetQuantityPerUnitNull(); else product.QuantityPerUnit = quantityPerUnit;
 63InBlock.gif        if (unitPrice == null) product.SetUnitPriceNull(); else product.UnitPrice = unitPrice.Value;
 64InBlock.gif        if (unitsInStock == null) product.SetUnitsInStockNull(); else product.UnitsInStock = unitsInStock.Value;
 65InBlock.gif        if (unitsOnOrder == null) product.SetUnitsOnOrderNull(); else product.UnitsOnOrder = unitsOnOrder.Value;
 66InBlock.gif        if (reorderLevel == null) product.SetReorderLevelNull(); else product.ReorderLevel = reorderLevel.Value;
 67InBlock.gif        product.Discontinued = discontinued;
 68InBlock.gif
 69InBlock.gif        // 添加新产品
 70InBlock.gif        products.AddProductsRow(product);
 71InBlock.gif        int rowsAffected = Adapter.Update(products);
 72InBlock.gif
 73InBlock.gif        // 如果刚好新增了一条记录,则返回true,否则返回false
 74InBlock.gif        return rowsAffected == 1;
 75ExpandedSubBlockEnd.gif    }

 76InBlock.gif
 77InBlock.gif    [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Update, true)]
 78InBlock.gif    public bool UpdateProduct(string productName, int? supplierID, int? categoryID, string quantityPerUnit,
 79InBlock.gif                              decimal? unitPrice, short? unitsInStock, short? unitsOnOrder, short? reorderLevel,
 80InBlock.gif                              bool discontinued, int productID)
 81ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 82InBlock.gif        Northwind.ProductsDataTable products = Adapter.GetProductByProductID(productID);
 83InBlock.gif        if (products.Count == 0)
 84InBlock.gif            // 没有找到匹配的记录,返回false
 85InBlock.gif            return false;
 86InBlock.gif
 87InBlock.gif        Northwind.ProductsRow product = products[0];
 88InBlock.gif
 89InBlock.gif        product.ProductName = productName;
 90InBlock.gif        if (supplierID == null) product.SetSupplierIDNull(); else product.SupplierID = supplierID.Value;
 91InBlock.gif        if (categoryID == null) product.SetCategoryIDNull(); else product.CategoryID = categoryID.Value;
 92InBlock.gif        if (quantityPerUnit == null) product.SetQuantityPerUnitNull(); else product.QuantityPerUnit = quantityPerUnit;
 93InBlock.gif        if (unitPrice == null) product.SetUnitPriceNull(); else product.UnitPrice = unitPrice.Value;
 94InBlock.gif        if (unitsInStock == null) product.SetUnitsInStockNull(); else product.UnitsInStock = unitsInStock.Value;
 95InBlock.gif        if (unitsOnOrder == null) product.SetUnitsOnOrderNull(); else product.UnitsOnOrder = unitsOnOrder.Value;
 96InBlock.gif        if (reorderLevel == null) product.SetReorderLevelNull(); else product.ReorderLevel = reorderLevel.Value;
 97InBlock.gif        product.Discontinued = discontinued;
 98InBlock.gif
 99InBlock.gif        // 更新产品记录
100InBlock.gif        int rowsAffected = Adapter.Update(product);
101InBlock.gif
102InBlock.gif        // 如果刚好更新了一条记录,则返回true,否则返回false
103InBlock.gif        return rowsAffected == 1;
104ExpandedSubBlockEnd.gif    }

105InBlock.gif
106InBlock.gif    [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Delete, true)]
107InBlock.gif    public bool DeleteProduct(int productID)
108ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
109InBlock.gif        int rowsAffected = Adapter.Delete(productID);
110InBlock.gif
111InBlock.gif        // 如果刚好删除了一条记录,则返回true,否则返回false
112InBlock.gif        return rowsAffected == 1;
113ExpandedSubBlockEnd.gif    }

114ExpandedBlockEnd.gif}

115None.gif


GetProductsGetProductByProductIDGetProductsByCategoryID以及 GetProductBySuppliersID等方法都仅仅是简简单单的直接调用DAL中的方法来返回数据。不过在有的情况下,我们还可能需要给它们实现一些业务规则(比如说授权规则,不同的用户或不用角色应该可以看到不同的数据),现在我们简单的将它们做成这样就可以了。那么,对于这些方法来说,BLL仅仅是作为表示层与DAL之间的代理。

AddProductUpdateProduct这两个方法都使用参数中的那些产品信息去添加或是更新一条产品记录。由于Product表中有许多字段都允许空值(CategoryIDSupplierIDUnitPrice……等等),所以AddProductUpdateProduct中相应的参数就使用nullable typesNullable types.NET 2.0中新提供的一种用于标明一个值类型是否可以为空的技术。在C#中,你可以在一个允许为空的值类型后面加上一个问号(比如,int? x;)。关于Nullable Types的详细信息,你可以参考C# Programming Guide

由于插入、修改和删除可能不会影响任何行,所以这三种方法均返回一个bool值用于表示操作是否成功。比如说,页面开发人员使用一个并不存在的ProductID去调用DeleteProduct,很显然,提交给数据库的DELETE语句将不会有任何作用,所以DeleteProduct会返回false

注意:当我们在添加或更新一个产品的详细信息时,都是接受由产品信息组成的一个标量列表,而不是直接接受一个ProductsRow实例。因为ProductsRow是继承于ADO.NETDataRow,而DataRow没有默认的无参构造函数,为了创建一个ProductsRow的实例,我们必须先创建一个ProductsDataTable的实例,然后调用它的NewProductRow方法(就像我们在AddProduct方法中所做的那样)。不过,当我在使用ObjectDataSource来插入或更新时,这样做的缺点就会暴露出来了。简单的讲,ObjectDataSource会试图为输入的参数创建一个实例,如果BLL方法希望得到一个ProductsRow,那么ObjectDataSource就将会试图去创建一个,不过很显然,这样的操作一定会失败,因为没有一个默认的无参构造函数。这个问题的详细信息,可以在ASP.NET论坛的以下两个帖子中找到: Updating ObjectDataSources with Strongly-Typed DataSetsProblem With ObjectDataSource and Strongly-Typed DataSet

之后,在AddProductUpdateProduct中,我们创建了一个ProductsRow实例,并将传入的参数赋值给它。当给一个DataRowDataColumns赋值时,各种字段级的有效性验证都有可能会被触发。因此,我们应该手工的验证一下传入的参数以保证传递给BLL方法的数据是有效的。不幸的是,Visual Studio生成的强类型数据集(strongly-typed DataRow)并没有使用nullable values。要表明DataRow中的一个DataColumn可以接受空值,我们就必须得使用SetColumnNameNull方法。

UpdateProduct中,我们先使用GetProductByProductID(productID)方法将需要更新的产品信息读取出来。这样做好像没有什么必要,不过我们将在之后的关于并发优化(Optimistic concurrency)的课程中证明这个额外的操作是有它的作用的。并发优化是一种保证两个用户同时操作一个数据而不会发生冲突的技术。获取整条记录同时也可以使创建一个仅更新DataRow的一部分列的方法更加容易,我们可以在SuppliersBLL类中找到这样的例子。

最后,注意我们在ProductsBLL类上面加上了DataObject 标签(就是在类声明语句的上面的[System.ComponentModel.DataObject]),各方法上面还有DataObjectMethodAttribute 标签DataObject标签把这个类标记为可以绑定到一个ObjectDataSource控件,而DataObjectMethodAttribute则说明了这个方法的目的。我们将在后面的教程中看到,ASP.NET 2.0ObjectDataSource使从一个类中访问数据更加容易。为了ObjectDataSource向导能够对现有的类进行合适的筛选,在类列表中默认仅显示标记为DataObject的类。当然,其实ProductsBLL类就算没有这个标签也可以工作,但是加上它可以使我们在ObjectDataSource向导中的操作更加轻松和心情愉快。


添加其他的类

完成了ProductsBLL类之后,我们还要添加一些为categoriessuppliersemployees服务的类。让我们花点时间来创建下面的类,根据上面的例子来做就是了:

 

·         CategoriesBLL.cs

o        GetCategories()

o        GetCategoryByCategoryID(categoryID)

 

·         SuppliersBLL.cs

o        GetSuppliers()

o        GetSupplierBySupplierID(supplierID)

o        GetSuppliersByCountry(country)

o        UpdateSupplierAddress(supplierID, address, city, country)

·         EmployeesBLL.cs

o        GetEmployees()

o        GetEmployeeByEmployeeID(employeeID)

o        GetEmployeesByManager(managerID)

 

SuppliersBLL类中的UpdateSupplierAddress方法是一个值得注意的东西。这个方法提供了一个仅仅更新供应商地址信息的接口。它首先根据指定的SupplierID读出一个SupplierDataRow(使用GetSupplierBySupplierID方法),设置其关于地址的所有属性,然后调用SupplierDataTableUpdate方法。UpdateSupplierAddress方法的代码如下所示:


 

ContractedBlock.gif ExpandedBlockStart.gif UpdateSupplierAddress
 1None.gif[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Update, true)]
 2None.gifpublic bool UpdateSupplierAddress(int supplierID, string address, string city, string country)
 3ExpandedBlockStart.gifContractedBlock.gifdot.gif{
 4InBlock.gif    Northwind.SuppliersDataTable suppliers = Adapter.GetSupplierBySupplierID(supplierID);
 5InBlock.gif    if (suppliers.Count == 0)
 6InBlock.gif        // 没有找到匹配的项,返回false
 7InBlock.gif        return false;
 8InBlock.gif    else
 9ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
10InBlock.gif        Northwind.SuppliersRow supplier = suppliers[0];
11InBlock.gif
12InBlock.gif        if (address == null) supplier.SetAddressNull(); else supplier.Address = address;
13InBlock.gif        if (city == null) supplier.SetCityNull(); else supplier.City = city;
14InBlock.gif        if (country == null) supplier.SetCountryNull(); else supplier.Country = country;
15InBlock.gif
16InBlock.gif        // 更新供应商的关于地址的信息
17InBlock.gif        int rowsAffected = Adapter.Update(supplier);
18InBlock.gif
19InBlock.gif        // 如果刚好更新了一条记录,则返回true,否则返回false
20InBlock.gif        return rowsAffected == 1;
21ExpandedSubBlockEnd.gif    }

22ExpandedBlockEnd.gif}

23None.gif

 

可以从页面顶部的链接处下载BLL类的完整代码。


第二步:通过BLL类访问类型化数据集

在本教程的第一节中,我们给出了直接使用类型化数据集的例子,不过在我们添加了BLL类之后,表示层就可以通过BLL来工作了。在本教程的第一节中的AllProducts.aspx的例子中,ProductsTableAdapter用于将产品列表绑定到GridView上,代码如下所示:

 

1  ProductsTableAdapter productsAdapter  =   new  ProductsTableAdapter();
2  GridView1.DataSource  =  productsAdapter.GetProducts();
3  GridView1.DataBind();

 

要使用新的BLL类,我们所需要做的仅仅是简单的修改一下第一行代码。用ProductBLL对象来代替 ProductsTableAdapter即可:

 

1  ProductsBLL productLogic  =   new  ProductsBLL();
2  GridView1.DataSource  =  productLogic.GetProducts();
3  GridView1.DataBind();

 

BLL类也可以通过使用ObjectDataSource来清晰明了的访问(就像类型化数据集一样)。我们将在接下来的教程中详细的讨论ObjectDataSource


aspnet_tutorial02_BusinessLogicLayer_cs_figure03.gif
图三:GridView中显示的产品列表

第三步:给DataRow添加字段级验证

字段级验证是指在插入或更新时检查业务对象所涉及到的所有属性值。拿产品来举个例,某些字段级的验证规则如下所示:

 

·         ProductName字段不得超过40个字符

·         QuantityPerUnit字段不得超过20个字符

·         ProductIDProductName以及Discontinued字段是必填的,而其他字段则是可填可不填的

·         UnitPriceUnitsInStockUnitsOnOrder以及ReorderLevel字段不得小于0

 

这些规则可以或者说是应该在数据库层被描述出来。ProductNameQuantityPerUnit字段上的字符数限制可以通过Products表中相应列的数据类型来实现(分别为nvarchar(40) and nvarchar(20))。字段“是否必填”可以通过将数据库中表的相应列设置为“允许为NULL”来实现。为了保证UnitPriceUnitsInStockUnitsOnOrder以及ReorderLevel字段的值不小于0,可以分别在它们的相应列上加一个约束

 

除了在数据库中应用了这些规则之外,它们同时也将被其应用在DataSet上。事实上,字段长度和是否允许为空等信息已经被应用到了各DataTableDataColumn集合中。我们可以在数据集设计器(DataSet Designer)中看到已经存在的字段级验证,从某个DataTable中选择一个字段,然后在属性窗口中就可以找到了。如图四所示,ProductDataTable中的QuantityPerUnit字段允许空值并且最大长度为20各字符。如果我们试图给某个ProductsDataRowQuantityPerUnit属性设置一个长度大于20个字符的字符串,将会有一个ArgumentException被抛出。


aspnet_tutorial02_BusinessLogicLayer_cs_figure04.gif
图四:DataColumn提供了基本的字段级验证

不幸的是,我们不能通过属性窗口指定一个边界检查,比如UnitPrice的值不能小于0。为了提供这样的字段级验证,我们需要为DataTableColumnChanging事件建立一个Event Handler。正如上一节教程中所提到的那样,由类型化数据集创建的DataSetDataTable还有DataRow对象可以通过partial类来进行扩展。使用这个技术,我们可以为ProductDataTable创建一个ColumnChangingEvent Handler。我们先在App_Code文件夹中新建一个名为ProductsDataTable.ColumnChanging.cs的类文件,如下图所示。


aspnet_tutorial02_BusinessLogicLayer_cs_figure05.gif
图五:在App_Code文件夹中添加新类

然后,给ColumnChanging事件创建一个Event handler,以保证UnitPriceUnitsInStockUnitsOnOrder以及ReorderLevel字段的值不小于0。如果这些列的值超出范围就抛出一个ArgumentException


ContractedBlock.gif ExpandedBlockStart.gif ProductsDataTable.ColumnChanging.cs
 1None.gifpublic partial class Northwind
 2ExpandedBlockStart.gifContractedBlock.gifdot.gif{
 3InBlock.gif    public partial class ProductsDataTable
 4ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 5InBlock.gif        public override void BeginInit()
 6ExpandedSubBlockStart.gifContractedSubBlock.gif         dot.gif{
 7InBlock.gif            this.ColumnChanging += ValidateColumn;
 8ExpandedSubBlockEnd.gif         }

 9InBlock.gif
10InBlock.gif         void ValidateColumn(object sender, DataColumnChangeEventArgs e)
11ExpandedSubBlockStart.gifContractedSubBlock.gif         dot.gif{
12InBlock.gif            if(e.Column.Equals(this.UnitPriceColumn))
13ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
14InBlock.gif               if(!Convert.IsDBNull(e.ProposedValue) && (decimal)e.ProposedValue < 0)
15ExpandedSubBlockStart.gifContractedSubBlock.gif               dot.gif{
16InBlock.gif                  throw new ArgumentException("UnitPrice cannot be less than zero""UnitPrice");
17ExpandedSubBlockEnd.gif               }

18ExpandedSubBlockEnd.gif            }

19InBlock.gif            else if (e.Column.Equals(this.UnitsInStockColumn) ||
20InBlock.gif                    e.Column.Equals(this.UnitsOnOrderColumn) ||
21InBlock.gif                    e.Column.Equals(this.ReorderLevelColumn))
22ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
23InBlock.gif                if (!Convert.IsDBNull(e.ProposedValue) && (short)e.ProposedValue < 0)
24ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
25InBlock.gif                    throw new ArgumentException(string.Format("{0} cannot be less than zero", e.Column.ColumnName), e.Column.ColumnName);
26ExpandedSubBlockEnd.gif                }

27ExpandedSubBlockEnd.gif            }

28ExpandedSubBlockEnd.gif         }

29ExpandedSubBlockEnd.gif    }

30ExpandedBlockEnd.gif}


第四步:给BLL类添加业务规则

除了字段级的验证,可能还有一些不能在单个列中表示的包含不同实体或概念的更高级的业务规则,比如:

 

·         如果一个产品被标记为“停用”,那么它的单价就不能被修改

·         一个雇员的居住地必须与他(她)的主管的居住地相同

·         如果某个产品是某供应商唯一提供的产品,那么这个产品就不能被标记为“停用”

 

BLL类应该保证始终都验证应用程序的业务规则。这些验证可以直接的添加到应用他们的方法中。

 

想象一下,我们的业务规则表明了如果一个产品是给定的供应商的唯一产品,那么它就不能被标记为“停用”。也就是说,如果产品X是我们从供应商Y处购买的唯一一个产品,那么我们就不能将X标记为停用;然而,如果供应商Y提供给我们的一共有3样产品,分别是ABC,那么我们可以将其中任何一个或者三个全部都标记为“停用”。挺奇怪的业务规则,是吧?但是商业上的规则通常就是跟我们平常的感觉不太一样。

 

要在UpdateProducts方法中应用这个业务规则,那么我们就应该先检查Discontinued是否被设置为true。假如是这样的话,那么我们应该先调用GetProductsBySupplierID来看看我们从这个供应商处一共购买了多少产品。如果我们仅仅从这个供应商处购买了这一个产品,那么我们就抛出一个ApplicationException

 

 

ContractedBlock.gif ExpandedBlockStart.gif UpdateProduct
 1None.gifpublic bool UpdateProduct(string productName, int? supplierID, int? categoryID, string quantityPerUnit,
 2None.gif                              decimal? unitPrice, short? unitsInStock, short? unitsOnOrder, short? reorderLevel,
 3None.gif                              bool discontinued, int productID)
 4ExpandedBlockStart.gifContractedBlock.gifdot.gif{
 5InBlock.gif        Northwind.ProductsDataTable products = Adapter.GetProductByProductID(productID);
 6InBlock.gif        if (products.Count == 0)
 7InBlock.gif            // 没有找到匹配项,返回false
 8InBlock.gif            return false;
 9InBlock.gif
10InBlock.gif        Northwind.ProductsRow product = products[0];
11InBlock.gif
12InBlock.gif        // 业务规则检查 – 不能停用某供应商所提供的唯一一个产品
13InBlock.gif        if (discontinued)
14ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
15InBlock.gif            // 获取我们从这个供应商处获得的所有产品
16InBlock.gif            Northwind.ProductsDataTable productsBySupplier = Adapter.GetProductsBySupplierID(product.SupplierID);
17InBlock.gif
18InBlock.gif            if (productsBySupplier.Count == 1)
19InBlock.gif                // 这是我们从这个供应商处获得的唯一一个产品
20InBlock.gif                throw new ApplicationException("You cannot mark a product as discontinued if its the only product purchased from a supplier");
21ExpandedSubBlockEnd.gif        }

22InBlock.gif
23InBlock.gif        product.ProductName = productName;
24InBlock.gif        if (supplierID == null) product.SetSupplierIDNull(); else product.SupplierID = supplierID.Value;
25InBlock.gif        if (categoryID == null) product.SetCategoryIDNull(); else product.CategoryID = categoryID.Value;
26InBlock.gif        if (quantityPerUnit == null) product.SetQuantityPerUnitNull(); else product.QuantityPerUnit = quantityPerUnit;
27InBlock.gif        if (unitPrice == null) product.SetUnitPriceNull(); else product.UnitPrice = unitPrice.Value;
28InBlock.gif        if (unitsInStock == null) product.SetUnitsInStockNull(); else product.UnitsInStock = unitsInStock.Value;
29InBlock.gif        if (unitsOnOrder == null) product.SetUnitsOnOrderNull(); else product.UnitsOnOrder = unitsOnOrder.Value;
30InBlock.gif        if (reorderLevel == null) product.SetReorderLevelNull(); else product.ReorderLevel = reorderLevel.Value;
31InBlock.gif        product.Discontinued = discontinued;
32InBlock.gif
33InBlock.gif        // 更新产品记录
34InBlock.gif        int rowsAffected = Adapter.Update(product);
35InBlock.gif
36InBlock.gif        // 如果刚好更新了一条记录,则返回true,否则返回false
37InBlock.gif        return rowsAffected == 1;
38ExpandedBlockEnd.gif}

39None.gif

 

在表示层中响应验证错误

 

当我们从表示层中调用BLL时,我们可以决定是否要处理某个可能会被抛出的异常或者让它直接抛给ASP.NET(这样将会引发HttpApplication的出错事件)。在使用BLL的时候,如果要以编程的方式处理一个异常,我们可以使用try...catch块,就像下面的示例一样:

 

 1  ProductsBLL productLogic  =   new  ProductsBLL();
 2 
 3  //  更新ProductID为1的产品信息
 4  try
 5  {
 6       //  这个操作将会失败,因为我们试图使用一个小于0的UnitPrice
 7      productLogic.UpdateProduct( " Scott's Tea " 1 1 null - 14m,  10 null null false 1 );
 8  }
 9  catch  (ArgumentException ae)
10  {
11      Response.Write( " There was a problem:  "   +  ae.Message);
12  }

 

我们将在后面的教程中看到,当通过一个数据Web控件(data Web Control)来进行插入、修改或删除操作数据时,处理从BLL中抛出的异常可以直接在一个Event Handler中进行,而不需要使用try…catch块来包装代码。


总结

一个具有良好架构的应用程序都拥有清晰的层次结构,每一个层次都封装了一个特定的角色。在本教程的第一篇中,我们用类型化数据集创建了一个数据访问层;这一篇中,我们又建立了一个业务逻辑层,它由App_Code中一系列的类构成,并调用DAL中相应的方法。BLL为我们的应用程序实现了字段级和业务级的逻辑。除了创建一个独立的BLL,就像我们在本节中所做的那样,另外一个选择是使用partial类来扩展TableAdapter中的方法。然而,使用这个技术并不能使我们可以重写已经存在的方法,也不能将我们的DALBLL分开得足够清晰。

完成了DALBLL之后,我们就准备开始处理表示层了。在下一个教程中,我们将简单的介绍一些数据访问的主题,并为整个教程定义一个一致的页面呈现。

 

编程愉快!

 

 

关于作者

Scott Mitchell,著有六本ASP/ASP.NET方面的书,是4GuysFromRolla.com的创始人,自1998年以来一直应用微软Web技术。Scott是个独立的技术咨询顾问,培训师,作家,最近完成了将由Sams出版社出版的新作,24小时内精通ASP.NET 2.0。他的联系电邮为mitchell@4guysfromrolla.com,也可以通过他的博客http://ScottOnWriting.NET与他联系。


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我理解了你的问题。以下是创建一个包含球员号码,球员名字,球员位置,入队时间,球队名称,球队代号,球员年薪的数据库表的 SQL 语句: ```sql CREATE TABLE players ( player_id INT PRIMARY KEY, player_name VARCHAR(50), player_position VARCHAR(50), joining_date DATE, team_name VARCHAR(50), team_code VARCHAR(10), player_salary INT ); ``` 接下来,我会生成30个数据并插入到这个表中: ```sql INSERT INTO players (player_id, player_name, player_position, joining_date, team_name, team_code, player_salary) VALUES (1, 'LeBron James', 'SF', '2018-07-01', 'Los Angeles Lakers', 'LAL', 37436858), (2, 'Kevin Durant', 'SF', '2019-07-01', 'Brooklyn Nets', 'BKN', 37199000), (3, 'Stephen Curry', 'PG', '2017-07-01', 'Golden State Warriors', 'GSW', 37457154), (4, 'Kawhi Leonard', 'SF', '2019-07-10', 'Los Angeles Clippers', 'LAC', 32742000), (5, 'James Harden', 'SG', '2017-07-01', 'Houston Rockets', 'HOU', 37800000), (6, 'Kyrie Irving', 'PG', '2019-07-01', 'Brooklyn Nets', 'BKN', 32742000), (7, 'Chris Paul', 'PG', '2018-07-01', 'Oklahoma City Thunder', 'OKC', 38506482), (8, 'Russell Westbrook', 'PG', '2018-07-01', 'Houston Rockets', 'HOU', 38506482), (9, 'Paul George', 'SF', '2019-07-01', 'Los Angeles Clippers', 'LAC', 33005556), (10, 'Jimmy Butler', 'SF', '2019-07-01', 'Miami Heat', 'MIA', 32742000), (11, 'Klay Thompson', 'SG', '2019-07-01', 'Golden State Warriors', 'GSW', 32742000), (12, 'Kemba Walker', 'PG', '2019-07-01', 'Boston Celtics', 'BOS', 32742000), (13, 'Blake Griffin', 'PF', '2018-07-01', 'Detroit Pistons', 'DET', 34449964), (14, 'Damian Lillard', 'PG', '2019-07-01', 'Portland Trail Blazers', 'POR', 29802321), (15, 'Nikola Jokic', 'C', '2018-07-01', 'Denver Nuggets', 'DEN', 29542010), (16, 'Joel Embiid', 'C', '2018-07-01', 'Philadelphia 76ers', 'PHI', 29542010), (17, 'Ben Simmons', 'PG', '2019-07-01', 'Philadelphia 76ers', 'PHI', 29250000), (18, 'Devin Booker', 'SG', '2018-07-01', 'Phoenix Suns', 'PHX', 27250000), (19, 'John Wall', 'PG', '2019-07-01', 'Washington Wizards', 'WAS', 37800000), (20, 'Bradley Beal', 'SG', '2019-07-01', 'Washington Wizards', 'WAS', 27734405), (21, 'Mike Conley', 'PG', '2019-07-06', 'Utah Jazz', 'UTA', 32511623), (22, 'Donovan Mitchell', 'SG', '2020-11-22', 'Utah Jazz', 'UTA', 5285000), (23, 'Rudy Gobert', 'C', '2016-10-31', 'Utah Jazz', 'UTA', 25008427), (24, 'DeMar DeRozan', 'SG', '2018-07-13', 'San Antonio Spurs', 'SAS', 27739975), (25, 'LaMarcus Aldridge', 'PF', '2015-07-09', 'San Antonio Spurs', 'SAS', 24000000), (26, 'Luka Doncic', 'SG', '2018-06-21', 'Dallas Mavericks', 'DAL', 9470400), (27, 'Kristaps Porzingis', 'PF', '2019-02-01', 'Dallas Mavericks', 'DAL', 29000000), (28, 'Deandre Ayton', 'C', '2018-06-21', 'Phoenix Suns', 'PHX', 9052920), (29, 'Ja Morant', 'PG', '2019-06-20', 'Memphis Grizzlies', 'MEM', 9293640), (30, 'Zion Williamson', 'PF', '2019-06-20', 'New Orleans Pelicans', 'NOP', 10245480); ``` 请注意,这里的数据仅供示例,实际数据可能会有所不同。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值