![]() |
Platforms, Frameworks & Libraries »
Libraries »
Code Libraries
License: The Code Project Open License (CPOL)
High Performance Reflection ORM LayerBy Andrew ChanBuilding a High Performance ORM Layer using ADO.NET, Reflection and Lambda Expressions |
C# (C# 1.0, C# 2.0, C# 3.0)
|
||||||||||
|
Advanced Search Add to IE Search |
|
|
|
||||||||||||||||
Mapping between a relational database and objects is traditionally a tedious exercise of mapping rows in a database to properties in a class. Many solutions have been created to make ORM a more pleasant experience for developers as a result. Automated code generation tools such as CodeSmith make ORM job easier by generating (data access layer) DAL code but results in a bloated DAL with thousands of lines of code. Frameworks such as NHibernate push mapping to XML and also gives the data access layer database independence, but the cost is a relatively heavy code for data access and still the need to map columns into properties. So what other solutions are there? Reflection!
Reflection is a much neglected way of providing an ORM layer. While the cost of reflection is heavy, if the mapping between the target object and the table is cached, theoretically the cost of reflection is only incurred on the first call, with all subsequent calls being retrieved from a cache. In this article I will go through how to write an efficient ORM using the System.Reflection namespace and C# 3.0's new lambda expressions.
Main Component Entry Point
The objective of our ORM layer is to give a nice way to translate from relational to a given strongly typed object. The interface I used is similiar to the DotNetNuke CBO class.
private static Dictionary<string, Func<IDataReader, object>> _mappingCache = new Dictionary<string, Func<IDataReader, object>>(); public static T CreateObject<T>(IDataReader dr) { string mappingSignature = dr.GetMappingSignature(typeof(T)); if (!_mappingCache.ContainsKey(mappingSignature)) { _mappingCache.Add(mappingSignature, CreateObjectMapping<T>(dr)); } return (T)_mappingCache[mappingSignature].Invoke(dr); }
This is the main entry method of our component. We give the static method a type T, and also pass in an IDataReader which contains our our relational data. The GetMappingSignature basically creates a string signature to uniquely identify the mapping between the given columns and the destination type. This is used so we can retrieve pre-cached mapping delegates later, bypassing the expensive reflection step. Our mapping cache is a lookup to find precached functions which provide the mapping between the IDataReader and the object.
Creating the Object Mapping Function
The essence of what we are trying to create is function which can return an object from a given row of data. Since we want to cache this construct for future use, we need a function which an input of IDataReader, and a return type of object, hence a Func<IDataReader, object>.
static Func<IDataReader, object> CreateObjectMapping<T>(IDataReader dataReader) { List<Action<IDataReader, object>> mapping = CreatePropertyMapping<T>(dataReader); return (IDataReader dr) => { object obj = CreateInstance<T>(); for (int i = 0; i < mapping.Count; i++) { Action<IDataReader, object> action = mapping[i]; action.Invoke(dr, obj); } return obj; }; }
This function does the bulk of the work in forming our mapping between the IDataReader and the object. It returns a function which creates an object of the given type with all its fields filled by the IDataReader. The List<Action<IDataReader, object>> contains the collection of assignment operations for each property in the type. CreateInstance<T>() is a method which creates an instance of a given type using a cached default constructor. A lambda expression is used to create a function dynamically using the mapping list in a closure (when an inner function referes to variables of the outer function).
Creating the Property Mapping Functions
Remember that our goal here is to programmatically work out how create data objects using only type information form our type T and relational information in the IDataReader. This mapping basically involves setting an object property with the values inside the corresponding column. To do this we will map our object property names against the column names
static List<Action<IDataReader, object>> CreatePropertyMapping<T>(IDataReader dr) { List<PropertyInfo> properties = Helper.GetPropertyInfo<T>(); List<Action<IDataReader, object>> mapping = new List<Action<IDataReader, object>>(); int i; for (i = 0; i < dr.FieldCount; i++) { string columnName = dr.GetName(i); //now find matching property PropertyInfo propMatch = (from p in properties where p.Name.ToLower() == columnName.ToLower() select p).FirstOrDefault(); if (propMatch != null) { Type columnType = dr.GetFieldType(i); Action<IDataReader, object> action = CreateSetValueAction(propMatch, columnType, columnName); mapping.Add(action); } } return mapping; }
Helper.GetPropertyInfo<T>() basically retrieves the property collection from a given type. CreateSetValueAction creates our assignment action based on the source data type and destination datatype. It also is responsible for working out type conversions for Enumerations and other things.
Usage of the Component
While the CreateObject<T>(IDataReader dr) function does the bulk of the work. It is necessary to use this component from a higher layer. I have included a small sample of how such a layer may look like might work.
Lamda Expressions are a extremely powerful new feature of C# 3.0. Use it!
| You must Sign In to use this message board. | ||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||
General
News
Question
Answer
Joke
Rant
Admin
|
PermaLink |
Privacy |
Terms of Use
Last Updated: 17 Dec 2007 Editor: |
Copyright 2007 by Andrew Chan Everything else Copyright © CodeProject, 1999-2009 Web18 | Advertise on the Code Project |