Introduction

A lot of times, I get a task to bind a relational model with an object designed model. Sometimes, I create an application engine with NHibernate, sometimes I use ADO.NET Entity Framework, but most of all I had to use DataTable and create a wrapper around DataTable objects with large "switch"s in it.

NHibernate is a good choice when you develop "Desktop" or "Web" applications, but it doesn't work in Compact Framework on Windows mobile, because CF doesn't support dynamic compilation. ADO.NET Entity Framework is a good choice for "new" applications designed in .NET 3.5 style. In this article, I want to show how to parse DataSet and create objects from it. You can download the source code from the link at the top of this article and use this little library.

Background

To test the application, you should install SQL Compact 3.5 and .NET 3.5. You can also use this library in .NET 2.0, but you should replace LINQ usages.

Using the Code

To show how it works, I create a simple database that includes 3 tables. The core of this system is generic class BusinessObject<T>. This class contains the necessary static methods that allow to get derived objects.

publicstatic List<T> Get(DataSet dataSet)

publicstatic List<T> Get(DataTable dataTable)

publicstatic T GetOne(DataSet dataSet)

publicstatic T GetOne(DataTable dataTable)

publicstatic T GetOne(DataRow row)

Steps to bind object:

Create a new class derived from BusinessObject<T>.

Create properties that correspond to fields in database and mark them with "BoFieldAttribute".

If a table has relations with other tables, create new properties and mark them with BoChildAttribute.

BoFieldAttribute - has constructor with argument "name". You should put a string which corresponds to ColumnName in DataTable.

This method is virtual and can be overriden in the derived class. It is very useful if we want to have the possibility to convert data in parse action. For example, we can store data in SQL Compact as image type and convert it to System.Drawing.Image or to ImageSource (WPF version).