Creating an ORM in C# - Part 6

Part 6 of the ORM creation series
Jul 06 2009 by James Craig

As always, I'm going to assume that you looked at the previous entries. So if you haven't, go take a look. This entry is just an addition to the last one (I would almost consider labeling it 5.5 instead of 6 actually). The last part of this series dealt with one to one class mappings and how we can deal with them in our relational database. It turns out it's fairly simple, with just a slight change from normal data (especially considering we implemented lazy loading). However I didn't get to the many to one and many to many mappings.
When dealing with one to one mappings, we could simply store the information as an extra entry in the table. With many to many though, that isn't an option. Instead we're basically dealing with a list. And like the lists that we've already dealt with, we need to set it up as a separate table. Thankfully, since we've already dealt with lists we're most of the way there. Anyway, let's start with the reflection and code generation:

 private void SetupManyToManyProperty(ILGenerator Generator,Type OriginalType)
{
Label ExitIfStatement = Generator.DefineLabel();
Label ExitIf2Statement = Generator.DefineLabel();
Label ExitStatement = Generator.DefineLabel();
Generator.DeclareLocal(Field.FieldType);
Generator.DeclareLocal(typeof(bool));
Generator.Emit(OpCodes.Nop);
Generator.Emit(OpCodes.Ldarg\_0);
Generator.Emit(OpCodes.Ldfld, Field.FieldBuilder);
Generator.Emit(OpCodes.Ldnull);
Generator.Emit(OpCodes.Ceq);
Generator.Emit(OpCodes.Ldc\_I4\_0);
Generator.Emit(OpCodes.Ceq);
Generator.Emit(OpCodes.Stloc\_1);
Generator.Emit(OpCodes.Ldloc\_1);
Generator.Emit(OpCodes.Brtrue\_S, ExitIfStatement);
Generator.Emit(OpCodes.Nop);
Generator.Emit(OpCodes.Call, typeof(HaterAide.Factory).GetMethod("CreateSession"));
Generator.Emit(OpCodes.Ldarg\_0);
Generator.Emit(OpCodes.Ldfld, IDField.FieldBuilder);
Generator.Emit(OpCodes.Box, IDField.FieldType);
Generator.Emit(OpCodes.Ldarg\_0);
Generator.Emit(OpCodes.Ldflda, Field.FieldBuilder);
Generator.Emit(OpCodes.Ldstr, \_Attribute.Name);
MethodInfo TempMethod = typeof(HaterAide.Session).GetMethod("SelectList");
TempMethod = TempMethod.MakeGenericMethod(new Type\[\] { OriginalType, Field.FieldType.GetGenericArguments()\[0\] });
Generator.Emit(OpCodes.Callvirt, TempMethod);
Generator.Emit(OpCodes.Nop);
Generator.Emit(OpCodes.Nop);
Generator.MarkLabel(ExitIfStatement);
Generator.Emit(OpCodes.Ldarg\_0);
Generator.Emit(OpCodes.Ldfld, Field.FieldBuilder);
Generator.Emit(OpCodes.Ldnull);
Generator.Emit(OpCodes.Ceq);
Generator.Emit(OpCodes.Ldc\_I4\_0);
Generator.Emit(OpCodes.Ceq);
Generator.Emit(OpCodes.Stloc\_1);
Generator.Emit(OpCodes.Ldloc\_1);
Generator.Emit(OpCodes.Brtrue\_S, ExitIf2Statement);
Generator.Emit(OpCodes.Nop);
Generator.Emit(OpCodes.Ldarg\_0);
Generator.Emit(OpCodes.Newobj, Field.FieldType.GetConstructor(new Type\[0\] { }));
Generator.Emit(OpCodes.Stfld, Field.FieldBuilder);
Generator.Emit(OpCodes.Nop);
Generator.MarkLabel(ExitIf2Statement);
Generator.Emit(OpCodes.Ldarg\_0);
Generator.Emit(OpCodes.Ldfld, Field.FieldBuilder);
Generator.Emit(OpCodes.Stloc\_0);
Generator.Emit(OpCodes.Br\_S, ExitStatement);
Generator.MarkLabel(ExitStatement);
Generator.Emit(OpCodes.Ldloc\_0);
Generator.Emit(OpCodes.Ret);
}

If you compared this to the one to one mapping, you actually wouldn't see much in terms of change. There is one change though, instead of getting the Select function, we are looking for the SelectList function in the Session class. And since the Session class is just a proxy, we may as well take a look at what it ends up calling:

 internal override object SelectListByID<T1, T2>(object IDValue, string FieldName)
{
Class TempInputClassDefinition = null;
Class TempOutputClassDefinition = null;
try
{
TempInputClassDefinition = ClassManager\[typeof(T1)\];
TempOutputClassDefinition = ClassManager\[typeof(T2)\];
}
catch { TempInputClassDefinition = null; TempOutputClassDefinition = null; }
return SQLBuilder.SelectListByID<T2>(ConnectionString, IDValue, TempInputClassDefinition, TempOutputClassDefinition, ClassManager, FieldName);
}

This in turn calls:

 internal static object SelectListByID<T>(string ConnectionString, object IDValue,
Class TempInputClassDefinition, Class TempOutputClassDefinition, ClassManager ClassManager,string FieldName)
{
Utilities.SQLHelper.SQLHelper Helper = new Utilities.SQLHelper.SQLHelper("", ConnectionString, CommandType.Text);
SelectManyToMany TempSelect = new SelectManyToMany(TempInputClassDefinition, TempOutputClassDefinition, ClassManager, FieldName);
return TempSelect.SelectByID<T>(IDValue, Helper);
}

Which in turn builds a SelectManyToMany class:

 internal class SelectManyToMany:IStatement
{
public SelectManyToMany(Class InputClass,Class OutputClass, ClassManager Manager,string FieldName)
: base(InputClass, Manager)
{
this.\_OutputClass = OutputClass;
this.\_FieldName = FieldName;
}

private Class \_OutputClass = null;
private string \_FieldName = "";

public object SelectByID<T>(object IDValue, SQLHelper Helper)
{
List<T> ReturnList = new List<T>();

foreach(Property TempProperty in \_Class.Properties)
{
if(TempProperty.Attribute.Name.Equals(\_FieldName))
{
Helper.Command=TempProperty.Attribute.MappedProperty+"\_Select\_"+\_Class.OriginalType.Name;
Helper.CommandType=CommandType.StoredProcedure;
break;
}
}
List<object\> IDList = LoadIDList(IDValue, Helper, ReturnList);
ReturnList=LoadList(IDList,Helper,ReturnList);
return ReturnList;
}

private List<T> LoadList<T>(List<object\> IDList,SQLHelper Helper,List<T> ReturnList)
{
Session TempSession=Factory.CreateSession();
foreach (object ID in IDList)
{
T ClassInstance = (T)Activator.CreateInstance(\_OutputClass.DerivedType);
TempSession.Select<T>(ID, out ClassInstance);
ReturnList.Add(ClassInstance);
}
return ReturnList;
}
private List<object\> LoadIDList<T>(object IDValue, SQLHelper Helper, List<T> ReturnList)
{
List<object\> IDList = new List<object\>();
IDataType IDField=GlobalFunctions.GetSQLType(\_Class.IDField,\_Class,\_Manager);
try
{
Helper.Open();
Helper.AddParameter("@" + \_Class.OriginalType.Name + "\_" + IDField.Name, IDValue, IDField.DataType);
Helper.ExecuteReader();
while (Helper.Read())
{
IDList.Add(Helper.GetParameter(\_OutputClass.OriginalType.Name + "\_" + \_OutputClass.IDField.Name, null));
}
}
catch { }
finally { Helper.Close(); }
return IDList;
}
}

The class works like the other IStatement classes. The big difference is that it loads a list instead of a single item. In fact since we already have a select function for a single entity, all it does is loads the list of IDs from the database and calls select on the individual IDs.
So we can load the items, but at present we have no table to actually pull the IDs from, we have no way to save them, etc. So let's start going down that road by defining a many to many data type.

 internal class ManyToManyClassType:IDataType
{
public ManyToManyClassType(Attribute Attribute, Class Class, ClassManager Manager)
: base(Attribute)
{
Type MappedType = Attribute.Type.GetGenericArguments()\[0\];
Class MappedClass = Manager\[MappedType\];
\_Class = Class;
\_Manager = Manager;
\_MappedClass = MappedClass;

MappedIDField = GlobalFunctions.GetSQLType(MappedClass.IDField, MappedClass, Manager);
IDField = GlobalFunctions.GetSQLType(Class.IDField, Class, Manager);
IDField.Constraints.Clear();
MappedIDField.Constraints.Clear();
}

public IDataType IDField { get; set; }
public IDataType MappedIDField { get; set; }
public Class \_Class = null;
public Class \_MappedClass = null;
public ClassManager \_Manager = null;

public override string CreateTableCommand()
{
StringBuilder Builder = new StringBuilder("CREATE TABLE " + Attribute.MappedProperty + "(" + Name + "ID int IDENTITY,");
Builder.Append(\_Class.OriginalType.Name + "\_" + IDField.CreateTableCommand() + ",");
Builder.Append(\_MappedClass.OriginalType.Name + "\_" + MappedIDField.CreateTableCommand());
Builder.Append(", PRIMARY KEY(" + Name + "ID)");
Builder.Append(")");
return Builder.ToString();
}

public override string CreateInsertCommand()
{
StringBuilder Builder = new StringBuilder("EXEC dbo.sp\_executesql @statement = N'CREATE PROCEDURE dbo." + Attribute.MappedProperty + "\_Insert\\n");
Builder.Append(IDField.CreateStoredProcedureParameter(false, true).Replace("@", "@" + \_Class.OriginalType.Name + "\_") + ",\\n");
Builder.Append(MappedIDField.CreateStoredProcedureParameter(false, true).Replace("@", "@" + \_MappedClass.OriginalType.Name + "\_"));
Builder.Append("\\nAS\\nINSERT INTO " + Attribute.MappedProperty + "(");
Builder.Append(\_Class.OriginalType.Name + "\_" + IDField.Name + ",");
Builder.Append(\_MappedClass.OriginalType.Name + "\_" + MappedIDField.Name + ") VALUES (");
Builder.Append("@"+\_Class.OriginalType.Name + "\_" + IDField.Name + ",");
Builder.Append("@" + \_MappedClass.OriginalType.Name + "\_" + MappedIDField.Name + ")\\nRETURN'\\n");
return Builder.ToString();
}

public override string CreateDeleteCommand()
{
StringBuilder Builder = new StringBuilder("EXEC dbo.sp\_executesql @statement = N'CREATE PROCEDURE dbo." + Attribute.MappedProperty + "\_Delete\_" + \_Class.OriginalType.Name + "\\n");
StringBuilder MappedBuilder = new StringBuilder("EXEC dbo.sp\_executesql @statement = N'CREATE PROCEDURE dbo." + Attribute.MappedProperty + "\_Delete\_" + \_MappedClass.OriginalType.Name + "\\n");

Builder.Append(IDField.CreateStoredProcedureParameter(false, true).Replace("@", "@" + \_Class.OriginalType.Name + "\_") + ",\\n");
MappedBuilder.Append(MappedIDField.CreateStoredProcedureParameter(false, true).Replace("@", "@" + \_MappedClass.OriginalType.Name + "\_"));

Builder.Append("\\nAS\\nDELETE FROM " + Attribute.MappedProperty + " WHERE ");
MappedBuilder.Append("\\nAS\\nDELETE FROM " + Attribute.MappedProperty + " WHERE ");

Builder.Append(\_Class.OriginalType.Name + "\_" + IDField.Name + "=");
Builder.Append("@" + \_Class.OriginalType.Name + "\_" + IDField.Name + "\\nRETURN'\\n");

MappedBuilder.Append(\_MappedClass.OriginalType.Name + "\_" + MappedIDField.Name + "=");
MappedBuilder.Append("@" + \_MappedClass.OriginalType.Name + "\_" + MappedIDField.Name + "\\nRETURN'\\n");

return Builder.ToString() + MappedBuilder.ToString();
}

public override string CreateSelectCommand()
{
StringBuilder Builder = new StringBuilder("EXEC dbo.sp\_executesql @statement = N'CREATE PROCEDURE dbo." + Attribute.MappedProperty + "\_Select\_" + \_Class.OriginalType.Name + "\\n");
StringBuilder MappedBuilder = new StringBuilder("EXEC dbo.sp\_executesql @statement = N'CREATE PROCEDURE dbo." + Attribute.MappedProperty + "\_Select\_" + \_MappedClass.OriginalType.Name + "\\n");

Builder.Append(IDField.CreateStoredProcedureParameter(false, true).Replace("@", "@" + \_Class.OriginalType.Name + "\_") + "\\n");
MappedBuilder.Append(MappedIDField.CreateStoredProcedureParameter(false, true).Replace("@", "@" + \_MappedClass.OriginalType.Name + "\_") + "\\n");

Builder.Append("\\nAS\\nSELECT "+\_Class.OriginalType.Name+"\_"+IDField.Name+","+\_MappedClass.OriginalType.Name+"\_"+MappedIDField.Name+" FROM "+Attribute.MappedProperty);
Builder.Append(" WHERE "+\_Class.OriginalType.Name+"\_"+IDField.Name+"=@"+\_Class.OriginalType.Name+"\_"+IDField.Name);

MappedBuilder.Append("\\nAS\\nSELECT " + \_Class.OriginalType.Name + "\_" + IDField.Name + "," + \_MappedClass.OriginalType.Name + "\_" + MappedIDField.Name + " FROM " + Attribute.MappedProperty);
MappedBuilder.Append(" WHERE " + \_MappedClass.OriginalType.Name + "\_" + MappedIDField.Name + "=@" + \_MappedClass.OriginalType.Name + "\_" + MappedIDField.Name);

Builder.Append("\\nRETURN'\\n");
MappedBuilder.Append("\\nRETURN'\\n");
return Builder.ToString() + MappedBuilder.ToString();
}
}

We did something similar with one to one mapped classes. As you can see we have our create table command, insert command, etc. And all we need to do is add the type to what our GlobalFunctions class returns and our statements should pick it up automatically (with some minor changes which you can find in the code linked to below). The big changes come when we actually try to save the item.

 private void SetupLists(object Object, SQLHelper Helper, Type ObjectType)
{
foreach (IDataType Column in Columns)
{
if (Column != null && Column is ManyToManyClassType)
{
ManyToManyClassType ManyToManyColumn = ((ManyToManyClassType)Column);
PropertyInfo IDPropertyInfo = ObjectType.GetProperty(ManyToManyColumn.\_Class.IDField.Name);
object IDValue = IDPropertyInfo.GetValue(Object, null);
Helper.Command = Column.Attribute.MappedProperty + "\_Insert";
PropertyInfo ListInfo = ObjectType.GetProperty(Column.Attribute.Name);
object ListValue = ListInfo.GetValue(Object, null);
if (ListValue != null)
{
Type ListType = ListValue.GetType();
PropertyInfo IndexProperty = ListType.GetProperty("Item");
PropertyInfo CountProperty = ListType.GetProperty("Count");
int Count = (int)CountProperty.GetValue(ListValue, null);
Type MappedObjectType = ManyToManyColumn.\_MappedClass.OriginalType;
PropertyInfo MappedIDPropertyInfo = MappedObjectType.GetProperty(ManyToManyColumn.\_MappedClass.IDField.Name);
for (int x = 0; x < Count; ++x)
{
object MappedClassObject = IndexProperty.GetValue(ListValue, new object\[\] { x });
object MappedClassID = MappedIDPropertyInfo.GetValue(MappedClassObject, null);
try
{
Helper.Open();
Helper.ClearParameters();
Helper.AddParameter("@" + ManyToManyColumn.\_Class.OriginalType.Name + "\_" + ManyToManyColumn.\_Class.IDField.Name, IDValue, ManyToManyColumn.IDField.DataType);
Helper.AddParameter("@" + ManyToManyColumn.\_MappedClass.OriginalType.Name + "\_" + ManyToManyColumn.\_MappedClass.IDField.Name, MappedClassID, ManyToManyColumn.MappedIDField.DataType);
Helper.ExecuteNonQuery();
}
catch { }
finally { Helper.Close(); }
}
}
}
else if (Column != null && (Column is List))//|| Column is ManyToManyClassType))
{
string IDName = ((List)Column).IDName;
SqlDbType IDType = ((List)Column).IDType;
string DataName = ((List)Column).DataName;
SqlDbType DataType = ((List)Column).DataType;
int DataSize = ((List)Column).Size;

PropertyInfo IDPropertyInfo = ObjectType.GetProperty(IDName);
object IDValue = IDPropertyInfo.GetValue(Object, null);

Helper.Command = Column.Name + "\_Insert";

PropertyInfo PropertyInfo = ObjectType.GetProperty(Column.Attribute.Name);
object ListValue = PropertyInfo.GetValue(Object, null);
if (ListValue != null)
{
Type ListType = ListValue.GetType();
PropertyInfo IndexProperty = ListType.GetProperty("Item");
PropertyInfo CountProperty = ListType.GetProperty("Count");
int Count = (int)CountProperty.GetValue(ListValue, null);
for (int x = 0; x < Count; ++x)
{
try
{
Helper.Open();
Helper.ClearParameters();
Helper.AddParameter("@" + IDName, IDValue, IDType);
if (DataType == SqlDbType.NVarChar)
{
Helper.AddParameter("@" + DataName, (string)IndexProperty.GetValue(ListValue, new object\[\] { x }), DataSize);
}
else
{
Helper.AddParameter("@" + DataName, IndexProperty.GetValue(ListValue, new object\[\] { x }), DataType);
}
Helper.ExecuteNonQuery();
}
catch { }
finally { Helper.Close(); }
}
}
}
}
}

You will see that we check if we're dealing with a ManyToManyClassType and if we are we find the list object, get each individual item, etc. in a similar manner to all lists thus far. However we have an added step of finding the ID for each individual object and inserting that into the table instead of the whole object. All we need to worry about is saving the connection to the correct object. The reason for this is that the object is already saved in another table. Our code for cascading a save handles this for us with only a little bit of extra code:

 private void CascadeSave(object Object, Type ObjectType)
{
Session TempSession = Factory.CreateSession();
foreach (IDataType Column in Columns)
{
if (Column.Attribute.Cascade)
{
PropertyInfo Property = ObjectType.GetProperty(Column.Name);
object Value=Property.GetValue(Object,null);
if (Value != null)
{
if (Column is ManyToManyClassType)
{
ManyToManyClassType ManyToManyColumn = ((ManyToManyClassType)Column);
Type ListType = Value.GetType();
PropertyInfo IndexProperty = ListType.GetProperty("Item");
PropertyInfo CountProperty = ListType.GetProperty("Count");
int Count = (int)CountProperty.GetValue(Value, null);
Type MappedObjectType = ManyToManyColumn.\_MappedClass.OriginalType;
for (int x = 0; x < Count; ++x)
{
object MappedClassObject = IndexProperty.GetValue(Value, new object\[\] { x });
TempSession.Save(MappedClassObject);
}
}
else
{
TempSession.Save(Value);
}
}
}
}
}

I've only shown you the insert function but the delete and update work in a similar manner. With that we have our insert, update, delete, and select functions working for many to many mappings. Now what about many to one?

To be honest, I've seen many to one mappings dealt with in many different ways. The most popular is to treat them as one sided one to one mappings when saving the data. For instance, let's assume we have a parent item that has multiple child items. The parent wouldn't save anything extra in this scenario; instead the child items would hold a link back to the parent item.

This works the vast majority of the time but I find that there is an issue if ever the code needs to change from a many to one to a many to many mapping (since that's usually more common than a switch to a one to one mapping).  So I decided to simply treat it like a many to many mapping. It gets its own table to store the links, its own stored procedures, etc. The only caveat is when we're saving, deleting, loading, etc. we have to check whether we're dealing with a list or a single item. If it's a list, we deal with it exactly as if it were a many to many mapping. In the single item scenario we treat it like a many to many mapping but we skip the reflection portions that deal with the list object. So half of the time we call Select and half the time we call SelectList. That's it really.

So at this point we can load, save, and delete pretty much anything we want. So on to dealing with the Caching right? Not quite. Sadly at this point we can only load a single item by its ID. That isn't exactly the most useful way to get our information. We still need to add a way to deal with that. That will be next time, but after that we're ready to deal with the Cache. Or at least I think so unless something comes up. So take a look at the code, leave feedback, and happy coding.