Tuesday, June 30, 2009

Pattern to fill collections for Object-relational mapping in C#.Net

Hi,
Now with generics creating collections is very easy in .Net.
but filling the collections with data has been a repeated coding job always.
This made me write this pattern by which we can create a new collection class in just couple of lines. This uses the same filling method used by ORM (Object-relational mapping ) object.



using System;
using System.Collections.Generic;
using System.Data;

namespace Prashant.Components.DBDataLister
{

// define a delegate for standard database retrival methods
public delegate IDataReader DBSelect(SearchParams Criteria);

// Interface of ORM
public interface IDBObject
{
void FillProperties(IDataReader dr);
}

// Interface of ORM collection
public interface IDBObjectList : System.Collections.IList
{
IDBObject NewItem();
}

// This class standizes the parameters for database retrival methods
public class SearchParams : Dictionary < string, string >
{
}

// The Collection filler class
internal static class DataLister
{

// The Fill method: Gets the data from db and fills the collection
// Paramters: 1) The List to fill
2) The method to get the data
3) Criteria for the filtering the data

internal static IDBObjectList FillData(IDBObjectList List,
DBSelect DoSelect, SearchParams Criteria)
{
IDataReader dr = DoSelect(Criteria);
while (dr.Read())
{
IDBObject objArr = List.NewItem();
objArr.FillProperties(dr);
List.Add(objArr);
}
return List;
}
}

}
// End



Now lets see how to use this in the sample below


using System;
using System.Collections.Generic;
using System.Data;
using Prashant.Components.DBDataLister;

namespace TestProj.Components
{
// A sample ORM class - for the database table Orders
public class Order : IDBObject // To enforce the FillProperties method
{
public string OrderNumber
{ get; private set; }
public string OrderDate
{ get; private set; }
public string Customer
{ get; private set; }

public void FillProperties(IDataReader dr)
{
OrderNumber = (string)dr["OrderNumber"];
OrderDate = (string)dr["OrderDate"];
Customer = (string)dr["Customer"];
}
}
// Data service Class/methods for the ORM
public class OrderService
{
public static IDataReader getOrderData(SearchParams Criteria)
{ // db retivial code goes here ...full code omited
IDataReader dr = DataService.getOrderList(.....);
return dr;
}
}


// This is the collection for Orders

public class OrderList : List < Order >, IDBObjectList
{
public IDBObject NewItem()
{
return (new Order());
}

// Returns the filled collection
public static OrderList getList(SearchParams Criteria)
{
return ((OrderList)DataLister.FillData(new OrderList(),
new DBSelect(OrderService.getOrderData), Criteria));

}

}


}


See the "OrderList" class sample given .
Your gridview cab be bound by

grv.Datasource = OrderList.getList(Criteria);