技术开发 频道

使用VS2005 DataSet设计器实现数据访问层



六、实现数据集的扩展

    当我们想使用data reader来代替一个data table时,或是对某一列的值加入更多的验证时,这些需求目前的设计器无法满足我们的要求。这就需要我们来为数据集来增加扩展类。如我们在当前工程中加入如下的类:

using System; using System.ComponentModel; using System.Data.SqlClient; using System.Data; namespace NorthwindDataAccess.EmployeesDataSetTableAdapters { public partial class EmployeesTableAdapter : Component { public SqlDataReader GetReader() { return Adapter.SelectCommand.ExecuteReader( CommandBehavior.CloseConnection); } } }

    我们现在就可以向table adapter中加入一个方法来执行SelectCommand。而不是用FillGetData方法。同样,如果你想为一列加入定制的验证,也可以通过扩展类来实现,代码如下:

namespace NorthwindDataAccess { public partial class EmployeesDataSet : DataSet { public partial class EmployeesDataTable : DataTable { public override void BeginInit() { this.ColumnChanging += ValidateColumn; } void ValidateColumn(object sender,DataColumnChangeEventArgs e) { if(e.Column.ColumnName == "BirthDate") { if((DateTime)e.ProposedValue < DateTime.Parse("1/1/1900")) { throw new ArgumentException( "Employee's productivity is likely to be very low"); } } } } } }

0
相关文章