asp tutorials, asp.net tutorials, sample code, and Microsoft news from 15Seconds
Data Access  |   Troubleshooting  |   Security  |   Performance  |   ADSI  |   Upload  |   Email  |   Control Building  |   Component Building  |   Forms  |   XML  |   Web Services  |   ASP.NET  |   .NET Features  |   .NET 2.0  |   App Development  |   App Architecture  |   IIS  |   Wireless
 
Pioneering Active Server
 Power Search








Active News
15 Seconds Weekly Newsletter
• Complete Coverage
• Site Updates
• Upcoming Features

More Free Newsletters
Reference
News
Articles
Archive
Writers
Code Samples
Components
Tools
FAQ
Feedback
Books
Links
DL Archives
Community
Messageboard
List Servers
Mailing List
WebHosts
Consultants
Tech Jobs
15 Seconds
Home
Site Map
Press
Legal
Privacy Policy
internet.commerce














internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

HardwareCentral
Compare products, prices, and stores at Hardware Central!

Designing N-Tiered Data Access Layer Using Datasets - Part 1
By David Catherman
Rating: 3.7 out of 5
Rate this article


  • email this article to a colleague
  • suggest an article

    Part 1 - Visual Studio Dataset Generator

    Introduction

    Microsoft has provided many rapid application development (RAD) tools with the Visual Studio 2005 (or 2008) environment. To handle your data access requirements, the typed dataset provides a great deal of functionality, but it has a deficiency that limits separation of layers into a clean N-tiered architecture. This article shows how to overcome the deficiency using code generation to build the missing data entity layer.

    Background

    A dataset is a collection of data tables and their relationships that represents a data entity structure for building data applications. Microsoft has taken the dataset to the next level in .NET 2.0 with the typed dataset. Visual Studio 2005 generates wrappers around the dataset to provide strong typed entity classes for accessing and manipulating the data and structure of a dataset which allows more bugs to be caught at compile time rather than runtime.

    The dataset generator can read the structure from a database and build a dataset from the selected tables matching the table entity and relationship structure. The table entity structure does not need to be identical to the database--tables and fields can be renamed and even combined or created as necessary like most object relation mapping (ORM) systems.

    Table adapters are generated to provide a layer of abstraction between the entity structure and the database. The methods provide a CRUD interface with the database and mapping of the tables and fields from the database to the entity tables, converting the specific data types to .NET (CLR) data types. The methods are specific to the type of database and can easily be regenerated when the data connection is changed to a different type of database. Among the databases supported are SQL Server, Oracle, Access, and many others through ODBC connection and 3rd party providers.

    The typed dataset is defined by an XSD schema and therefore can easily be serialized to XML for the interoperability and portability needed for service applications.

    Data Sources

    Another RAD tool available in Visual Studio 2005 is the Data Sources window pane when developing Windows (Smart Client) applications. (The data sources are available for binding in Web apps also, but do not have the advanced screen layout tools of Win apps.) The data sources pane can read any data entity object, but is specially geared to work with typed datasets. If the dataset is physically located in the same Windows project, even the CRUD can be automatically generated. This makes for a very powerful RAD tool but does not adhere to N-tiered architecture since the presentation layer directly calls the data access layer.

    Data Source solves this problem by providing an Object type of connection which points to an existing entity object and allows much of the same data binding and control layout tools. These entity objects can either be datasets or hand crafted classes with properties and collections to emulate a data structure. The advantage is that the objects can be in a different project, allowing tier separation. The disadvantage is that Visual Studio no longer generates the CRUD methods, leaving the developer to hand craft the necessary code. This is the deficiency that is dealt with in this article.

    Using Datasets as an Object Relational Mapping (ORM) Tool

    There are many ORM tools available on the market, some expensive and some relatively inexpensive, and most do a good job of generating data entities and some even generate the data structure for business objects. If you have the budget and don't mind working with the pre-defined architecture, then pick one and go with it. Another option is to use the power of datasets as an ORM tool.

    Here are some of the requirements for a good ORM tool:

    1. Provide a tool to generate a data entity structure of classes, properties and collections that are the building blocks of business objects.

    2. Allow mapping of entities and entity attributes to tables and fields in a database.

    3. Generate the CRUD methods to persist the data to the database and allow the queries to easily be customized.

    4. Provide a means to relate data in parent-child or lookup value list relationships.

    5. A good ORM tool should also provide a good visual editor for piecing together entities into business objects.

    Datasets meet most of these requirements and with the additions provided by this article, meet all of them well. The visual editor sets the standard for ease of use and is more comprehensive than most ORM tools. It scans a database to provide the template to create entities with mapping to the persisted form. It provides a visual SQL editor to fashion queries easily for specific CRUD definition. It shows visually the relationships between entities, and it stores the information directly in a schema format. The entities and relationships combine to form the domain model structure of a business object.

    The generator uses the schema to generate code for the classes and collections that make up the entities. It generates additional methods to handle the relations between entities, and it generates the table adapters to allow the entities to interact with the database to persist the data. For a simple structure with two average sized entities, it generates around 2000 lines of code.

    The Dataset Generator

    Here is a quick tutorial on how the dataset generator works in Visual Studio 2005. To get the most from the system, use the Data Sources wizard--in the top line Data menu, click on the "Add New Data Source" option. The wizard begins by selecting or creating a connection. Select the server and the NorthWind database. The next screen shows a list of all the objects in the database:

    Expand the tree and select the objects you wish to represent in the dataset. Usually, tables will be selected, but views and stored procedures may be selected as well. Be sure to give the dataset a meaningful name--usually the business object name.

    Completing this wizard will create a typed dataset in your project. In this article, a multi-tiered application is the goal so the dataset must be created in (or moved to) a separate Class Library type of "Business Layer" project. Open the new dataset from the Solution Explorer (has an ".xsd" extension). The visual editor will show a representation of the two entities and their relationship.

    More tables or objects can be added by dragging and dropping from the Server explorer. Entity names and field names may be edited, added, or deleted as necessary using the properties and the contextual menus.

    On the bottom of each entity is the table adapter used to associate the entity with the persisted table in the data store. By default, the Fill (an existing table in the dataset), GetData (returns a data table object), and if possible, the Update methods are added automatically. (Update handles insert, update, and delete functions.)

    The queries that link the table data to the entity data can be edited by right clicking on the adapter and selecting "Configure.." to launch a wizard.

    The first screen shows the SQL statement to select the data. The SQL can be edited directly here or click the "Query Builder…" button to visually edit the SQL.

    The four part editor shows the table(s) in the top pane, a list of fields with sorting and filtering in the second pane, the generated (also editable) SQL in the third pane, and after clicking the "Execute Query" button, the results of the query in the bottom pane.

    Back on the Wizard, the "Advanced Options" button allows the update functions to be edited. Checkboxes allow the update function to be deselected (for lookup tables) saving generated lines of code, using optimistic concurrency (deselecting this will save a few lines of generated code), and automatic table refresh after update.

    The next screen of the wizard allows the user to select and edit the names of the three different types of methods created to accomplish the CRUD.

    The last screen shows a summary of all the classes and methods that are generated by the dataset.

    From the dataset editor, you may also right click the table adapter and choose to add a new query for the entity to select data in a different manner by using parameters. The results of the query should return exactly the same fields, but can join several tables and require parameters to filter data. This is a good way to provide a fill by relation functionality to only select child records to match the record(s) selected in the parent table.

    What Was Generated?

    Here is a look into the Object Browser to see what Visual Studio generated for us.

    In the dataset namespace is the dataset itself, a typed data table to contain the collection of rows for each table, a typed row object for each table to expose a single instance of each row, and the event handlers. In the same file, but in a separate namespace is the table adapter for each table that is persisted in the database.

    The type dataset inherits from System.Data.DataSet for a good deal of its functionality, but also adds a lot of functionality from generated code.

    Other than initialization and serialization methods, it has collection of table, a collection of relations, and properties to return the typed version of each data table.

    The typed data table contains methods and events for changing and deleting a row, and data columns for each field in the data table.

    Of note are the AddCustomerRow (two different overloads), and FindByCustomerID (the primary key of the table) methods which are very useful.

    The typed data row has another set of properties and methods.

    There is a typed property for each column that allows access to the field data. .NET has a problem handling null data, so several methods are added for each nullable field to check for null and to set to null.

    The table adapters do not have a base type to inherit from except for component, so all the functionality must be generated into methods.

    There are methods to Fill an existing data table, return a data table with GetData, and several overloads for the Update method. Several methods like Insert and Delete take each of the fields as parameters to add a new record and delete a record with concurrence.

    The command collection contains the SQL to select, insert, update, and delete records, and any special queries.

    What Is Missing?

    In a tiered architecture, each tier can only access the tier either above or below it. The data access is handled by the table adapters and should not be called by the presentation layer. The business layer should expose methods to retrieve and update data. Specifically, each entity in the business object should have the methods necessary for persisting its data. These methods need to be added to the data table objects that contain the entity. Basically it is just a wrapper to instantiate the table adapter and call the appropriate method on it. Each data table needs a method to Fill itself and Update any edits and if needed, a method for wrapping the GetData function to return a data table.

    The second missing feature is the ability to modify the SQL at runtime to filter the records returned. The best way to do this is to use the visual editor to create select queries as necessary to filter the data before it is loaded. But there are times when you need to change the SQL on the fly for complex relational data retrieval.

    Part 2 of this article will cover how to implement these missing features to complete a great ORM tool.

    Recap of Using Datasets

    The Good:

    • Datasets have a good structure for handling collections of data well (as compared to the alternative of using collections or array lists). The data tables and data rows are well suited to processing data in memory.

    • The class wrappers generated for the data tables and rows provide strong typing, Intellisense in the code editor, and compile time error catching. The data entity structure is modeled well and highly functional.

    • Methods are generated to handle the infrastructure needed for initialization, serialization, creating, deleting, relating, finding, strong typing, and changing data.

    • The table adapters abstract and wrap all of the ADO.NET provider specific code to persist the data to the database.

    The Bad:

    • Some developers criticize datasets as being heavy weight, generating properties and methods that may never be used.

    • The class wrappers do not include wrappers for the data access logic to preserve the tier separation.

    • Table adapters do not allow runtime customization of the SQL queries.

    • Entity structure and table adapter methods are generated into the same file, restricting the capability of physically separating the tiers into separate projects (but they are separated by namespace.)

    About The Author

    David Catherman

    Email: David (dot) Catherman (at) Hotmail (dot) com

    David Catherman has 20+ years designing and developing database applications with specific concentration for the last 5-6 years on Microsoft .NET and SQL Server. He is currently working as an Application Architect and Senior Developer using Visual Studio 2005 and SQL Server 2005. He has several MCPs in .NET and is pursuing MCSD.

    References

  • Rate This Article
    Not HelpfulMost Helpful
    1 2 3 4 5
    Other Articles
    Jul 21, 2005 - N-Tier Web Applications using ASP.NET 2.0 and SQL Server 2005 - Part 1
    While the .NET Framework made building ASP.NET applications easier then it had ever been in the past, .NET 2.0 builds on that foundation in order to take things to the next level. This article shows you to how to construct an N-Tier ASP.NET 2.0 Web application by leveraging the new features of ASP.NET 2.0 and SQL Server 2005.
    [Read This Article]  [Top]
    Apr 28, 2005 - New Files and Folders in ASP.NET 2.0
    With the release of ASP.NET 2.0, Microsoft has greatly increased the power of ASP.NET by introducing a suite of new features and functionalities. As part of this release, ASP.NET 2.0 also comes with a host of new special files and folders that are meant to be used to implement a specific functionality. This article examines these new files and folders in detail and provides examples that demonstrate how to utilize them to create ASP.NET 2.0 applications.
    [Read This Article]  [Top]
    Mar 10, 2005 - The DataSet Grows Up in ADO.NET 2.0 - Part 2, Cont'd
    Alex Homer continues his detailed look at the major changes to the DataSet class. In this part, he looks at two features that allow developers to work with data in a more structured and efficient way when using the DataSet with a SQL Server 2005 database server.
    [Read This Article]  [Top]
    Mar 9, 2005 - The DataSet Grows Up in ADO.NET 2.0 - Part 2
    Alex Homer continues his detailed look at the major changes to the DataSet class. In this part, he looks at two features that allow developers to work with data in a more structured and efficient way when using the DataSet with a SQL Server 2005 database server.
    [Read This Article]  [Top]
    Mar 3, 2005 - The DataSet Grows Up in ADO.NET 2.0 - Part 1, Cont'd
    In this article, Alex Homer looks at the changes between the version 1.x and version 2.0 DataSet and their associated classes, showing you how you can take advantage of the new features to improve your applications' capabilities and performance.
    [Read This Article]  [Top]
    Mar 2, 2005 - The DataSet Grows Up in ADO.NET 2.0 - Part 1
    In this article, Alex Homer looks at the changes between the version 1.x and version 2.0 DataSet and their associated classes, showing you how you can take advantage of the new features to improve your applications' capabilities and performance.
    [Read This Article]  [Top]
    Feb 16, 2005 - Writing a Custom Membership Provider for the Login Control in ASP.NET 2.0
    In ASP.NET 2.0 and Visual Studio 2005, you can quickly program custom authentication pages with the provided Membership Login controls. In this article, Dina Fleet Berry examines the steps involved in using the Login control with a custom SQL Server membership database.
    [Read This Article]  [Top]
    Dec 29, 2004 - ClickOnce Deployment in .NET Framework 2.0
    In this article, Thiru Thangarathinam examines .NET 2.0's new ClickOnce deployment technology that is designed to ease deployment of Windows forms applications. This new technology not only provides an easy application installation mechanism, it also eases deployment of upgrades to existing applications.
    [Read This Article]  [Top]
    Dec 15, 2004 - A Sneak Peek at ASP.NET 2.0's Administrative Tools
    With ASP.NET 2.0, Microsoft has made great strides in increasing developer productivity and has made implementing previously complex solutions relatively easy. Where this version of ASP.NET really shines, however, is in its new administrative tools that allow developers to spend less time managing the configuration of the servers and software and more time developing great code.
    [Read This Article]  [Top]
    Nov 17, 2004 - The ASP.NET 2.0 TreeView Control
    Thiru Thangarathinam introduces ASP.NET 2.0's new TreeView control which provides a seamless way to consume and display information from hierarchical data sources. The article discusses this new control in depth and explains how to use this feature rich control in your ASP.NET applications.
    [Read This Article]  [Top]
    Mailing List
    Want to receive email when the next article is published? Just Click Here to sign up.

    Support the Active Server Industry



    JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

    Solutions
    Whitepapers and eBooks
    Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
    Microsoft Article: 7.0, Microsoft's Lucky Version?
    Microsoft Article: Hyper-V--The Killer Feature in Windows Server 2008
    Avaya Article: How to Feed Data into the Avaya Event Processor
    Microsoft Article: Install What You Need with Windows Server 2008
    HP eBook: Putting the Green into IT
    Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
    Avaya Article: Setting Up a SIP A/S Development Environment
    IBM Article: How Cool Is Your Data Center?
    Microsoft Article: Managing Virtual Machines with Microsoft System Center
    HP eBook: Storage Networking , Part 1
    Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
    MORE WHITEPAPERS, EBOOKS, AND ARTICLES
    Webcasts
    Intel Video: Are Multi-core Processors Here to Stay?
    On-Demand Webcast: Five Virtualization Trends to Watch
    HP Video: Page Cost Calculator
    Intel Video: APIs for Parallel Programming
    HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
    Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
    MORE WEBCASTS, PODCASTS, AND VIDEOS
    Downloads and eKits
    Sun Download: Solaris 8 Migration Assistant
    Sybase Download: SQL Anywhere Developer Edition
    Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
    Red Gate Download: SQL Compare Pro 6
    Iron Speed Designer Application Generator
    MORE DOWNLOADS, EKITS, AND FREE TRIALS
    Tutorials and Demos
    How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
    eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
    IBM Article: Collaborating in the High-Performance Workplace
    HP Demo: StorageWorks EVA4400
    Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
    Microsoft How-to Article: Get Going with Silverlight and Windows Live
    MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES