使用自定义实体类和集合代替DataSet

http://www.microsoft.com/china/msdn/library/webservices/asp.net/custentcls.mspx
【另】:更多参考资料和链接也见原文,强烈推荐

dataset的问题:
1、缺少抽象,开发人员必须了解其基础架构;
2、弱类型,返回的是system.object,必须进行类型转换convert.toint32等之后才能使用,降低了效率,增加了出错的可能性;
3、不是面向对象的,无法充分利用oo的技术。
使用dataset,它的缺点将在复杂系统中成倍的扩大。

自定义实体类的挑战:
要求更多的代码。我们不是简单地获取数据并自动填充 dataset,而是获取数据并手动将数据映射到自定义实体(必须先创建好)。由于这个工作是重复的,我们可以使用代码生成工具或者orm映射。

自定义实体类的代码示例:
public class user {
#region "fields and properties"
private int userid;
private string username;
private string password;
public int userid {
get { return userid; }
set { userid = value; }
  }
public string username {
get { return username; }
set { username = value; }
}
public string password {
get { return password; }
set { password = value; }
}
#endregion
#region "constructors"
public user() {}
public user(int id, string name, string password) {
this.userid = id;
this.username = name;
this.password = password;
}
#endregion
}

自定义实体类的优点:
1、可以让我们利用继承和封装等oo技术;
2、可以添加自定义行为;
3、属于强类型,可以获得代码自动完成功能(intellisense);
4、属于强类型,不太需要容易出错的强制类型转换。

对象和关系的映射:
public user getuser(int userid) {
sqlconnection connection = new sqlconnection(connection_string);
sqlcommand command = new sqlcommand("getuserbyid", connection);
command.parameters.add("@userid", sqldbtype.int).value = userid;
sqldatareader dr = null;
try{
connection.open();
dr = command.executereader(commandbehavior.singlerow);
if (dr.read()){
user user = new user();
user.userid = convert.toint32(dr["userid"]);
user.username = convert.tostring(dr["username"]);
user.password = convert.tostring(dr["password"]);
return user;           
  }
return null;
}finally{
if (dr != null && !dr.isclosed){
dr.close();
  }
connection.dispose();
command.dispose();
}
}

以上代码还保留着dataset弱类型需要转换这样的缺点,所以应该进一步改进,即将映射的转换过程提取到一个函数中,使这段代码能够重复使用——

public user populateuser(idatarecord dr) {
user user = new user();
user.userid = convert.toint32(dr["userid"]);
//检查 null 的示例
if (dr["username"] != dbnull.value){
user.username = convert.tostring(dr["username"]);  
}
user.password = convert.tostring(dr["password"]);
return user;
}

需要说明1:我们不对映射函数使用 sqldatareader,而是使用 idatarecord。这是所有 datareader 实现的接口。使用 idatarecord 使我们的映射过程独立于供应商。也就是说,我们可以使用上一个函数从 access 数据库中映射 user,即使它使用 oledbdatareader 也可以。如果您将这个特定的方法与 provider model design pattern(链接 1链接 2)结合使用,您的代码就可以轻松地用于不同的数据库提供程序。
需要说明2:数据访问是否该和自定义实体类放在一起?为了扩展和维护的方便,通常应该将数据访问层和业务层明确分离。

自定义集合:
简单的解决方案是使用arraylist,但它的问题和dataset相关,即也是弱类型,无法添加自定义行为。幸亏 microsoft .net framework 提供了一个专门为了此目的而继承的类:collectionbasecollectionbase 的工作原理是,将所有类型的对象都存储在专有 arraylist 中,但是通过只接受特定类型(例如 user 对象)的方法来提供对这些专有集合的访问。代码示例——

public class usercollection :collectionbase {
public user this[int index] {
get {return (user)list[index];}
set {list[index] = value;}
}
public int add(user value) {
return (list.add(value));
}
public int indexof(user value) {
return (list.indexof(value));
}
public void insert(int index, user value) {
list.insert(index, value);
}
public void remove(user value) {
list.remove(value);
}
public bool contains(user value) {
return (list.contains(value));
}
}

映射到自定义集合:
将我们的关系数据映射到自定义集合的过程与我们对自定义实体执行的过程非常相似。我们不再创建一个实体并将其返回,而是将该实体添加到集合中并循环到下一个:

public usercollection getallusers() {
sqlconnection connection = new sqlconnection(connection_string);
sqlcommand command =new sqlcommand("getallusers", connection);
sqldatareader dr = null;
try{
connection.open();
dr = command.executereader(commandbehavior.singleresult);
usercollection users = new usercollection();
while (dr.read()){
users.add(populateuser(dr));
  }
return users;
}finally{
if (dr != null && !dr.isclosed){
dr.close();
  }
connection.dispose();
command.dispose();
}
}

添加自定义行为:
示例一
public user finduserbyid(int userid) {
foreach (user user in list) {
if (user.userid == userid){
return user;
  }
}
return null;
}
示例二
public usercollection findmatchingusers(string search) {
if (search == null){
throw new argumentnullexception("search cannot be null");
}
usercollection matchingusers = new usercollection();
foreach (user user in list) {
string username = user.username;
if (username != null && username.startswith(search)){
matchingusers.add(user);
  }
}
return matchingusers;
}

绑定自定义集合:
自定义集合绑定到web控件和dataset一样很简单(这是因为 collectionbase 实现了用于绑定的 ilist)。自定义集合可以作为任何控件的 datasource,而 databinder.eval 只能像您使用 dataset 那样使用——

usercollection users = dal.getallusers();
repeater.datasource = users;
repeater.databind();

<!-- html -->
<asp:repeater onitemdatabound="r_idb" id="repeater" runat="server">
<itemtemplate>
<asp:label id="username" runat="server">
<%# databinder.eval(container.dataitem, "username") %><br />
</asp:label>
</itemtemplate>
</asp:repeater>

高级内容:
1、并发
2、性能
3、排序与筛选
4、代码生成
5、orm映射
6、泛型
7、可以为空的类型
8、迭代程序

【强烈推荐参考:《dataset与自定义实体类以及集合的比较》】
datasets vs. collections by dino esposito对比分析了dataset, typed dataset和custom entities and collections(定制业务实体和集合)作为multi-tier之间的数据传递,并阐述各自的适用情况(when to use which)。

文章建议:在小型项目中,考虑到预算、截至时间等因素,可以使用dataset快速开发。如果项目时间长、投入多,业务逻辑复杂,则使用自定义实体类以及集合,对于维护、扩展、灵活、代码的优雅、单元测试等,都能带来益处。前期的投入是值得的。

文章建议阅读:for more information on these topics, take a look at the following blogs: scott hanselmans at returning datasets from webservices is the spawn of satan and represents all that is truly evil in the world, jelle druyts at datasets are not evil, andrew conrads at nix the dataset??????, and objectsharp at dataset faq.

各项比较:

  dataset typed dataset custom entities
built-in support for concurrency yes yes to be added
data relationship yes yes no
serialization inefficient in .net framework 1.x same as dataset, but can be improved to be added
null values no yes to be added
schema abstraction yes yes yes
strong typing no yes yes
support for hierarchical data yes, but through a relational api yes, but through a relational api yes
free-form data no no yes
custom behavior no to be added yes
ease of development yes yes no, but can be improved through custom wizards and code generation
.net data binding yes yes to be added; requires the implementation of several additional interfaces
interfacing with web services costly, unless knowledge of the object is assumed on the client schema information is more precise and can be handled by the client yes
xml integration yes yes to be added
expression language yes yes to be added
data aggregation yes yes to be added

如果采用custom entities,建议了解如下常用的enterprise design patterns:
design patterns for building a dal

pattern
description
active record
the entity object stores its own data as well as any available methods. clients get an instance of the object and work with it as needed.
data mapper
the entity object contains only its own data. a neat separation exists between data and behavior. behavior is delegated to an array of separate classes specific to the object.
table data gateway
variation of data mapper that delegates the implementation of required behaviors to external, gateway classes not specific to the object. the gateway can take scalar and instance data and serve multiple business objects.

posted on 2007-10-16 10:36 尹智玲 阅读(...) 评论(...)  编辑 收藏

导航

公告