Thursday, December 10, 2009

Building own ORM tool using .net Reflection

All professional .net programmer know about System.Reflection. Through it, you can extract meta information of a class or assembly. Using reflection testing tools, ORM tools etc. can be developed.

Here is a sample how you can develop your own ORM tool using .net Reflectin. It is similar to LINQ and obviously not at all so powerful like LINQ. But it has the superiority over the LINQ in the sense that it can run on any Database. Suppose you have a class Student which has properties like public long Student_Id, public string Student_Name. Like LINQ you must have a table Table Students which has columns student_id number, student_name varchar2(256).

So, if you want to get the list of Student from Database to application you need to use C# generic. Steps are as follows -

1. Use typeof() to get object type.

2. List it properties from the Type object using GetProperties() of type object.

3. Generate sql query - class name maps the table name and property names map the column names.

4. Get the data from database.

5. Invoke set method of the object to set property to the database column values. Example code can be like this -
MethodInfo method = _methodList.FirstOrDefault(m => m.Name == "set_" + property.Name);
method.Invoke(typedObject, paramObjects);
6. Return the list.

This is the high-level algorithm of this simple ORM.