Creating an ORM in C# - Part 5

Part 5 of the ORM creation series
Jun 30 2009 by James Craig

Today I finally got around to adding support for classes... Well straight one to one mappings anyway, many to many and many to one are a bit trickier so I've put those off for another post. As always, you may want to read the earlier posts if you haven't already. But in this post I'm going to cover loading of classes, lazy loading, and cascading updates/inserts.

Basically when you think about it, as far as our CRM is concerned, a class is just another data type. However unlike say an int, we really don't want to load it when the rest of the class is loaded. I mean we can but that would potentially cause issues (we might end up loading our entire database or even end up in an endless loop of loading). So what most people do to combat this is use something called lazy loading. Lazy loading is simply a design pattern where you load/initialize an object only when it is needed. So how do we go about setting up our system to do lazy loading?

 public Property(Attribute Attribute, TypeBuilder TypeBuilder, FieldBuilder ChangedField,ClassManager Manager)
{
Field = new Field(Attribute, TypeBuilder, FieldAttributes.Private);
if (Attribute.AttributeType == AttributeType.Map)
{
Attribute TempIDAttribute = new Attribute();
TempIDAttribute.AttributeType = Attribute.AttributeType;
Class TempClass = Manager\[Attribute.Type\];
foreach (Property TempProperty in TempClass.Properties)
{
if (TempProperty.Attribute.AttributeType == AttributeType.ID)
{
TempIDAttribute.Type = TempProperty.Attribute.Type;
}
}
TempIDAttribute.Name = Attribute.Name + "ID";
IDField = new Field(TempIDAttribute, TypeBuilder, FieldAttributes.Public);
}
MethodAttributes GetSetAttributes = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.Virtual;
MethodBuilder ValuePropertyGet = TypeBuilder.DefineMethod("get\_" + Attribute.Name, GetSetAttributes, Attribute.Type, Type.EmptyTypes);
ILGenerator Generator = ValuePropertyGet.GetILGenerator();
if (Attribute.AttributeType == AttributeType.Map)
{
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);
MethodInfo TempMethod = typeof(HaterAide.Session).GetMethod("Select");
TempMethod = TempMethod.MakeGenericMethod(new Type\[\] { Field.FieldType });
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);
}
else
{
Generator.Emit(OpCodes.Ldarg\_0);
Generator.Emit(OpCodes.Ldfld, Field.FieldBuilder);
Generator.Emit(OpCodes.Ret);
}


MethodBuilder ValuePropertySet = TypeBuilder.DefineMethod("set\_" + Attribute.Name, GetSetAttributes, null, new Type\[\] { Attribute.Type });

Generator = ValuePropertySet.GetILGenerator();

Generator.Emit(OpCodes.Ldarg\_0);
Generator.Emit(OpCodes.Ldarg\_1);
Generator.Emit(OpCodes.Stfld, Field.FieldBuilder);
Generator.Emit(OpCodes.Ldarg\_0);
Generator.Emit(OpCodes.Ldfld, ChangedField);
Generator.Emit(OpCodes.Ldstr, Attribute.Name);
Generator.Emit(OpCodes.Callvirt, typeof(List<string\>).GetMethod("Add"));
Generator.Emit(OpCodes.Ret);

\_Attribute = Attribute;
}

As you can see above the Property constructor has been changed slightly. There are two sections that check if the attribute type is a mapping. These are our updates to deal with classes. The first section defines an ID field (the ID of the mapped class will go there when we load it). The second section is the actual code for getting the object. It checks whether the object is null, if it is null it loads the object and saves it for later (by creating a session object and simply calling Select), however if it is still null it creates a default object. Either way, it returns whatever is held in the object. Now the only tricky thing in here is the fact that Select is a generic function. It took me a good hour to figure out that while I could get the function itself easily enough that I had to define what type it should use. That's done with the MakeGenericMethod call. It seems simple once you've seen it but you'll hit your head against the wall for a while if you don't know what to do as the exceptions that are returned are fairly useless...

Anyway, that's it; we now have lazy loading and classes working... Ok, we still have some slight issues with the database, but the lazy loading is set up and our reflection is working properly. At this point though, we aren't setting up the tables or stored procedures to hold the class mappings. So how do we do this? Well because of how I've set up the SQL building, all we really need to do is create a new data type:

 internal class MapClassType:IDataType
{
public MapClassType(Attribute Attribute, Reflection.Class Class, ClassManager Manager)
: base(Attribute)
{
\_Class = Class;
\_Manager = Manager;

MappedClass = \_Manager\[Attribute.Type\];
MappedDataType = GlobalFunctions.GetSQLType(MappedClass.IDField, MappedClass, \_Manager);
DataType = MappedDataType.DataType;
Type = MappedDataType.Type;
}

private Class \_Class = null;
private ClassManager \_Manager = null;
public Class MappedClass { get; set; }
public IDataType MappedDataType { get; set; }

public override string CreateTableCommand()
{
StringBuilder Builder = new StringBuilder(Name + " " + MappedDataType.Type);
return Builder.ToString();
}
}

internal static class GlobalFunctions
{
public static IDataType GetSQLType(Attribute Attribute,Class Class,ClassManager Manager)
{
if (Attribute.Type.FullName.Equals("System.Int32", StringComparison.CurrentCultureIgnoreCase))
{
return new HaterAide.SQL.SQLServer.Statements.DataTypes.Int(Attribute);
}
else if (Attribute.Type.FullName.Equals("System.String", StringComparison.CurrentCultureIgnoreCase))
{
return new HaterAide.SQL.SQLServer.Statements.DataTypes.NVarChar(Attribute);
}
else if (Attribute.Type.FullName.Equals("System.Single", StringComparison.CurrentCultureIgnoreCase))
{
return new HaterAide.SQL.SQLServer.Statements.DataTypes.Float(Attribute);
}
else if (Attribute.Type.FullName.Equals("System.Double", StringComparison.CurrentCultureIgnoreCase))
{
return new HaterAide.SQL.SQLServer.Statements.DataTypes.Float(Attribute);
}
else if (Attribute.Type.FullName.Equals("System.Boolean", StringComparison.CurrentCultureIgnoreCase))
{
return new HaterAide.SQL.SQLServer.Statements.DataTypes.Bit(Attribute);
}
else if (Attribute.Type.FullName.StartsWith("System.DateTime", StringComparison.CurrentCultureIgnoreCase))
{
return new HaterAide.SQL.SQLServer.Statements.DataTypes.DateTime(Attribute);
}
else if (Attribute.Type.FullName.StartsWith("System.Guid", StringComparison.CurrentCultureIgnoreCase))
{
return new HaterAide.SQL.SQLServer.Statements.DataTypes.UniqueIdentifier(Attribute);
}
else if (Attribute.Type.FullName.StartsWith("System.Collections.Generic.List", StringComparison.CurrentCultureIgnoreCase))
{
return new HaterAide.SQL.SQLServer.Statements.DataTypes.List(Attribute, Class, Manager);
}
if (Attribute.AttributeType == AttributeType.Map)
{
return new HaterAide.SQL.SQLServer.Statements.DataTypes.MapClassType(Attribute, Class, Manager);
}
return null;
}
}

As you can see, it acts similarly to the List class in that it doesn't use its own information but instead uses the ID field of the class that it maps to. And after we add it to the global function so that it's being returned, Insert, Select, Update, and Delete classes will simply pick it up and use it properly for the table/stored procedures that are created.
So we have our table that can store the class's ID so that it can load and map the classes properly. However we now have to deal with the more annoying part. We need to actually set up the various stored procedures such that they can use the ID properly.

 private void SetupProperties(object Object, SQLHelper Helper, Type ObjectType)
{
foreach (IDataType Column in Columns)
{
if (Column != null && Column is MapClassType)
{
MapClassType TempColumn = (MapClassType)Column;
object MappedObject=ObjectType.GetProperty(TempColumn.Name).GetValue(Object,null);
if (MappedObject != null)
{
Type MappedObjectType = MappedObject.GetType();
object Value = MappedObjectType.GetProperty(TempColumn.MappedClass.IDField.Name).GetValue(MappedObject, null);
Helper.AddParameter("@" + TempColumn.Name, Value, TempColumn.MappedDataType.DataType);
}
else if(TempColumn.MappedDataType.DataType==SqlDbType.Int)
{
Helper.AddParameter("@" + TempColumn.Name, 0, TempColumn.MappedDataType.DataType);
}
else if (TempColumn.MappedDataType.DataType == SqlDbType.UniqueIdentifier)
{
Helper.AddParameter("@" + TempColumn.Name, Guid.Empty, TempColumn.MappedDataType.DataType);
}
}
else if (Column != null && !Column.Type.Equals("List", StringComparison.CurrentCultureIgnoreCase))
{
PropertyInfo PropertyInfo = ObjectType.GetProperty(Column.Name);
object Value = PropertyInfo.GetValue(Object, null);
if (Column is NVarChar && !Column.IsPrimaryKey)
{
foreach (IConstraint Constraint in Column.Constraints)
{
if (Constraint is Size)
{
Helper.AddParameter("@" + Column.Name, (string)Value, ((Size)Constraint).Length);
break;
}
}
}
else if (!Column.IsPrimaryKey)
{
Helper.AddParameter("@" + Column.Name, Value, Column.DataType);
}
}
}
}

Above is a function from the Insert class. The function looks for nonlist items and adds them to the stored procedure. The top part checks if the individual column is a mapped class. Inside that if statement, it first gets the object's value. If the object is not null it gets the object's ID field and the value of that field. It then adds that value into the stored procedure.  A similar addition is made to the Update class. The Delete class doesn't require any updates at all since the only thing the stored procedure cares about is the ID of the class. The Select class is slightly different.

 private object LoadMainClass(object IDValue, SQLHelper Helper, object ClassInstance, IDataType IDField)
{
try
{
Helper.Open();
if (IDField is NVarChar)
{
foreach (IConstraint Constraint in IDField.Constraints)
{
if (Constraint is Size)
{
Helper.AddParameter("@" + IDField.Name, (string)IDValue, ((Size)Constraint).Length);
}
}
}
else
{
Helper.AddParameter("@" + IDField.Name, IDValue, IDField.DataType);
}
Helper.ExecuteReader();
if (Helper.Read())
{
ClassInstance = Activator.CreateInstance(\_Class.DerivedType);
foreach (IDataType Column in Columns)
{
if (Column != null && Column is MapClassType)
{
FieldInfo TempField = \_Class.DerivedType.GetField("\_" + Column.Name + "IDDerived");
TempField.SetValue(ClassInstance, Helper.GetParameter(Column.Name, null));
}
else if (Column != null && !Column.Type.Equals("List", StringComparison.CurrentCultureIgnoreCase))
{
PropertyInfo TempProperty = \_Class.DerivedType.GetProperty(Column.Name);
if (TempProperty.PropertyType.FullName.Equals("System.Single", StringComparison.CurrentCultureIgnoreCase))
{
TempProperty.SetValue(ClassInstance, float.Parse(Helper.GetParameter(Column.Name, null).ToString()), null);
}
else
{
TempProperty.SetValue(ClassInstance, Helper.GetParameter(Column.Name, null), null);
}
}
}
}
}
catch { }
finally { Helper.Close(); }
return ClassInstance;
}

Luckily we've set the mapped classes ID field in a predictable manner. So what we do is go through the list of columns like before and if we see a MapClassType object, we get the ID field that we created back in the reflection stage. We then set that value to the ID value that we have stored in our database. We don't load the entire mapped class, just the ID, and we let the lazy loading that we set up before handle the rest.

Now we have our table, our stored procedures, and our lazy loading. That just leaves cascading saving of objects. This is actually slightly more difficult than it may look on the surface. Take for instance two classes, each have a mapping to one another. We save class A which then cascades to class B which then cascades to class A... Yay, infinite loop. Luckily a while back I set up the definitions to take in a boolean stating whether or not to do cascading on a specific property. So we simply set it up such that class B says don't update class A where as class A says cascade down to B. This just means that the person defining the relationship needs to be careful but that's the only issue. So for the Insert and Update classes we simply add a call to the function below from the Run function.

 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)
{
TempSession.Save(Value);
}
}
}
}

That's it really. We check our properties, we check if they're null, and we save them. And since we've dealt with the infinite loop issue, we can actually make this function pretty dumb. Now you may assume that we're done but there is yet one more thing that needs to be done. Specifically when we're inserting an object for the first time, there is an issue. You see the order of operations when inserting is we first insert the main class information, we get back our new ID and set that in the object, insert our lists, and then cascade our insertion. Now what happens when the objects that it cascades haven't been saved before? Their ID is going to be the default value (so 0 for an int, etc.). So when we first saved the initial object, all of those mapped classes are pointing to the class with an ID of 0. So how do we fix this? Well after the cascade, these items have an ID as they've been inserted. So at this point all that we need to do is update the main class (we can skip the lists, etc.). So we add this function:

 private void UpdateMainProperties(object Object, Type ObjectType,SQLHelper Helper)
{
try
{
Helper.Command = \_Class.OriginalType.Name + "\_Update";
Helper.Open();
foreach (IDataType Column in Columns)
{
if (Column != null && Column is MapClassType)
{
MapClassType TempColumn = (MapClassType)Column;
object MappedObject = ObjectType.GetProperty(TempColumn.Name).GetValue(Object, null);
if (MappedObject != null)
{
Type MappedObjectType = MappedObject.GetType();
object Value = MappedObjectType.GetProperty(TempColumn.MappedClass.IDField.Name).GetValue(MappedObject, null);
Helper.AddParameter("@" + TempColumn.Name, Value, TempColumn.MappedDataType.DataType);
}
else if (TempColumn.MappedDataType.DataType == SqlDbType.Int)
{
Helper.AddParameter("@" + TempColumn.Name, 0, TempColumn.MappedDataType.DataType);
}
else if (TempColumn.MappedDataType.DataType == SqlDbType.UniqueIdentifier)
{
Helper.AddParameter("@" + TempColumn.Name, Guid.Empty, TempColumn.MappedDataType.DataType);
}
}
else if (Column != null && !Column.Type.Equals("List", StringComparison.CurrentCultureIgnoreCase))
{
PropertyInfo PropertyInfo = ObjectType.GetProperty(Column.Name);
object Value = PropertyInfo.GetValue(Object, null);
if (Column is NVarChar && !Column.IsPrimaryKey)
{
foreach (IConstraint Constraint in Column.Constraints)
{
if (Constraint is Size)
{
Helper.AddParameter("@" + Column.Name, (string)Value, ((Size)Constraint).Length);
break;
}
}
}
else
{
Helper.AddParameter("@" + Column.Name, Value, Column.DataType);
}
}
}
Helper.ExecuteNonQuery();
}
catch { }
finally { Helper.Close(); }
}

We could simply call Save again but our system is pretty dumb and would simply call cascade again. We don't want to deal with that so a simple update function works well enough. And with that function we're finally done with classes. Well one to one mapped classes anyway. We have yet to deal with the pain which is many to many and many to one. But hey, the CRM is getting closer to being done. So give it a try, leave feedback, and happy coding.