Use a set of custom object classes instead of Dataset

Source: Internet
Author: User

WebServices is used in recent projects. The WebServices method is called and sqldatareader cannot be returned. The following message is displayed: sqldatareader cannot be serialized,
Dataset is okay, of course... one of them is that when sqldatareader is used, Conn should be connected...

However, sometimes using dataset is a waste of resources, so I reprinted this article.Article:

For more information about ASP. NET: Introduction to custom object classes (Chinese), see:
Http://www.microsoft.com/china/msdn/library/webservices/asp.net/CustEntCls.mspx
[Note]: For more references and links, see the original article. We strongly recommend that you

Dataset problems:
1. Developers must understand their infrastructure in the absence of abstraction;
2. Weak type. system. object is returned and must be converted to convert. toint32 before use. This reduces the efficiency and increases the possibility of errors;
3. the OO technology cannot be fully utilized because it is not object-oriented.
When dataset is used, its disadvantages will multiply in complex systems.

Challenges of custom object classes:
MoreCode. We are not simply getting data and filling it automaticallyDatasetInstead, you can obtain the data and manually map the data to a custom object (you must first create the object ). Because this work is repeated, we can use the code generation tool or ORM ing.

Sample Code for custom object classes:
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
}

Advantages of custom object classes:
1. We can use inheritance, encapsulation, and other oo technologies;
2. You can add custom behaviors;
3. It is a strong type and can obtain the Automatic Code Completion function (intelliisense );
4. It is a strong type and does not require error-prone forced type conversion.

Ing between objects and relationships:
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 ();
}
}

The above Code retains the disadvantages of weak dataset type conversion, so further improvement should be made to extract the ing conversion process to a function so that this code can be reused --

Public user populateuser (idatarecord Dr ){
User user = new user ();
User. userid = convert. toint32 (Dr ["userid"]);
// Null check example
If (Dr ["username"]! = Dbnull. Value ){
User. Username = convert. tostring (Dr ["username"]);
}
User. Password = convert. tostring (Dr ["password"]);
Return user;
}

Note 1: We do not use the ing function.SqldatareaderInsteadIdatarecord. This is allDatareaderImplemented interface. UseIdatarecordMake our ing process independent from the supplier. That is to say, we can use the previous function to map data from the ACCESS database.User, Even if it usesOledbdatareaderOr. If you use this method in combination with Provider Model Design Pattern (link 1 and link 2), your code can be easily used in different databases.Program.
NOTE 2: Should data access be put together with custom object classes? To facilitate expansion and maintenance, the data access layer and service layer should be clearly separated.

Custom set:
The simple solution is to use arraylist, but its problems are related to dataset, which is also a weak type and cannot be used to add custom behaviors. Fortunately, Microsoft. NET Framework provides a class specifically inherited for this purpose:Collectionbase.CollectionbaseThe principle is to store all types of objects in a proprietaryArraylistBut only accept a specific type (for exampleUserObject) to provide access to these proprietary sets. Code example --

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 ));
}
}

Map to a custom set:
The process of ing our relational data to a custom set is very similar to the process of executing a custom object. Instead of creating an object and returning it, we add the object to the set and loop to the next one:

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 ();
}< br> connection. dispose ();
command. dispose ();
}< BR >}

Add custom behavior:
Example 1
Public user finduserbyid (INT userid ){
Foreach (User user in list ){
If (user. userid = userid ){
Return user;
}
}
Return NULL;
}
Example 2
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;
}

Bind a custom set:
Binding a custom set to a web control is as easy as dataset (this is becauseCollectionbaseImplemented for bindingIlist). A custom set can be used as any control'sDatasource, AndDatabinder. EvalOnlyDatasetUse it in that way --

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>

Advanced content:
1. Concurrency
2. Performance
3. Sorting and filtering
4. Code Generation
5. Orm ing
6. Generic
7. Can be empty
8. Iterative Program

[Strongly recommended reference: Comparison between dataset and custom object classes and sets]
Datasets vs. CollectionsBy Dino Esposito compares and analyzes dataset, typed dataset, and custom entities and collections (custom business entities and sets) as data transmission between multi-tier, and explain their respective applicability (when to use which ).

Suggestion: dataset can be used for quick development in small projects based on budget, deadline, and other factors. If the project takes a long time, invests a lot, and the business logic is complex, the use of custom entity classes and collections can bring benefits to maintenance, expansion, flexibility, code elegance, unit testing, and so on. The initial investment is worthwhile.

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 edevil in the world, jelle druyts at datasets are not edevil, andrew conrads at nix the dataset ??????, And objectsharp at dataset FAQ.

Comparison:

  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 into action 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
Development 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
If you use custom entities, we recommend that you understand the following commonly used 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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.