Thursday, July 06, 2006

Why I rarely use ADO.NET Datasets

Have you ever seen these great presentations which teach you how to build a master-details web page in a few minutes without writing a single line of code using a combination of DataSets, TableAdapters, ObjectDataSources, GridViews and FormViews? There is a great one at http://download.microsoft.com/download/8/3/6/836dd5f8-fa92-499f-8219-0d326f13bf18/hilo_data_final.wmv.

There are sound technical reasons not to use DataSets in ASP.NET applications due to their stateful nature. These reasons are explained by Frans Bouma in his blog at http://weblogs.asp.net/fbouma/archive/2003/05/13/6966.aspx. I have experienced other reasons not to use DataSets as a business layer.

The entity-relationship model (the way data is organised in database) rarely corresponds so perfectly (see the video mentioned above) to the way you are going to present it. You will need to go through various transformations, for example:

  • You may have an invoice which is constituted of items and you need to present the invoice total which is actually the total of all item amounts. This total may also need to be presented in several currencies.

  • You may have an N-N relationship between messages and contacts in your database, but you need to display a message with a To, Cc and Bcc fields which are separated lists of email addresses.
Data is rarely presented in the way it is stored in database and a business layer gives you the objects that you need between data and presentation, for example:

  • You need to store UTC dates which will have to be converted using the time zone defined in your user’s profile;

  • You need to store country codes which will have to be mapped to localized country names;

  • You need to store a document status as a byte like 0, 1 and 2, which will have to be mapped to an enumerated value like “draft”, “approved” and “rejected”.
You also need to validate data before storing it in database. You can use validation controls in your presentation layer, but their features are limited and it is good practice to implement business rules in a business layer.

So what should we do?

  1. Implement your data access layer (DAL) as stored procedures handling create, read, update and delete (CRUD) operations;

  2. Implement a business logic layer (BLL) in C# or VB.NET calling stored procedures using data readers and commands, which will achieve much better performances.
Then when do you use datasets?
  1. You only use datasets in rapid application development (RAD) scenarios, or when

  2. You have no other choice, for example when a component that you need (otherwise you would spend hours reinventing the wheel) requires datasets.

No comments: