Using Enterprise Library to Map Data Into Objects (Simple ORM)


In a recent project – working with developers just started using MS Enterprise Library – I had the need to implement a simple framework for them to deal with relational database as objects in a simple ORM.

The idea was to create a layer utilizing Enterprise Library 6.0 to encapsulate the database objects mapping plus having a way for validation.

The solution can be highlighted as below:

 image

First, we have implemented a base Adapter of T – T is the object type – as the following:

1 /// <summary> 2 /// The base class for the adapter 3 /// </summary> 4 /// <typeparam name="T">The type of the associated object</typeparam> 5 public class AdapterBase<T> 6 { 7 /// <summary> 8 /// Gets the object. 9 /// </summary> 10 /// <param name="objectData">The object data.</param> 11 /// <returns>One instance of the associated object</returns> 12 protected static T GetObject(DataRow objectData) 13 { 14 var objectInstance = (T)Activator.CreateInstance(typeof(T)); 15 16 var databaseDefinedProperties = ExploreDatabaseDefinedProperties(objectInstance); 17 18 return GetObject(objectData, databaseDefinedProperties); 19 } 20 21 /// <summary> 22 /// Gets the collection. 23 /// </summary> 24 /// <param name="collectionData">The collection data.</param> 25 /// <returns>Collection of the associated object</returns> 26 protected static Collection<T> GetCollection(DataTable collectionData) 27 { 28 var objectCollection = (Collection<T>)Activator.CreateInstance(typeof(Collection<T>)); 29 30 var objectInstance = (T)Activator.CreateInstance(typeof(T)); 31 32 var databaseDefinedProperties = ExploreDatabaseDefinedProperties(objectInstance); 33 34 foreach (DataRow row in collectionData.Rows) 35 { 36 objectCollection.Add(GetObject(row, databaseDefinedProperties)); 37 } 38 39 return objectCollection; 40 } 41 42 /// <summary> 43 /// Gets the object. 44 /// </summary> 45 /// <param name="objectData">The object data.</param> 46 /// <param name="databaseDefinedProperties">The database defined properties.</param> 47 /// <returns></returns> 48 private static T GetObject(DataRow objectData, Collection<PropertyInfo> databaseDefinedProperties) 49 { 50 var objectInstance = (T)Activator.CreateInstance(typeof(T)); 51 52 foreach (PropertyInfo propertyInfo in databaseDefinedProperties) 53 { 54 if (Attribute.IsDefined(propertyInfo, typeof(DbField))) 55 { 56 var dbAttribute = propertyInfo.CustomAttributes.Single(p => p.AttributeType == typeof(DbField)); 57 58 if (dbAttribute != null) 59 { 60 var dbFieldName = dbAttribute.NamedArguments.Single(p => p.MemberName == "DbfieldName").TypedValue.Value.ToString(); 61 62 if (objectData.Table.Columns.Contains(dbFieldName)) 63 { 64 var dbFieldValue = objectData[dbFieldName]; 65 66 if (dbFieldValue != DBNull.Value) 67 { 68 propertyInfo.SetValue(objectInstance, objectData[dbFieldName]); 69 } 70 } 71 } 72 73 } 74 } 75 return objectInstance; 76 } 77 78 /// <summary> 79 /// Explores the database defined properties. 80 /// </summary> 81 /// <param name="objectInstance">The object instance.</param> 82 /// <returns></returns> 83 private static Collection<PropertyInfo> ExploreDatabaseDefinedProperties(T objectInstance) 84 { 85 var databaseDefinedProperties = new Collection<PropertyInfo>(); 86 87 var info = objectInstance.GetType().GetTypeInfo(); 88 89 foreach (PropertyInfo propertyInfo in info.DeclaredProperties) 90 { 91 if (Attribute.IsDefined(propertyInfo, typeof(DbField)) && propertyInfo.CanWrite) 92 { 93 databaseDefinedProperties.Add(propertyInfo); 94 } 95 } 96 97 return databaseDefinedProperties; 98 } 99 100 /// <summary> 101 /// Validates the specified object to validate. 102 /// </summary> 103 /// <param name="objectToValidate">The object to validate.</param> 104 /// <returns></returns> 105 public static ValidationResults Validate(T objectToValidate) 106 { 107 return Validation.Validate<T>(objectToValidate); 108 } 109 110 /// <summary> 111 /// Validates the specified object to validate. 112 /// </summary> 113 /// <param name="objectToValidate">The object to validate.</param> 114 /// <param name="ruleSet">The rule set.</param> 115 /// <returns></returns> 116 public static ValidationResults Validate(T objectToValidate, string[] ruleSet) 117 { 118 return Validation.Validate<T>(objectToValidate, ruleSet); 119 } 120 121 public static string ToXml(T objectToConvert) 122 { 123 var objectXml = new XmlDocument(); 124 125 var parentNode = objectXml.CreateElement("ObjectData"); 126 127 var info = objectToConvert.GetType().GetTypeInfo(); 128 129 foreach (PropertyInfo propertyInfo in info.DeclaredProperties) 130 { 131 var xmlNode = objectXml.CreateElement(propertyInfo.Name); 132 var nodeValue = propertyInfo.GetValue(objectToConvert); 133 xmlNode.InnerText = nodeValue == null ? "" : nodeValue.ToString(); 134 parentNode.AppendChild(xmlNode); 135 } 136 137 objectXml.AppendChild(parentNode); 138 139 return objectXml.InnerXml; 140 } 141 142 143 }

The base adapter have the needed functions to convert relational data – Data Tables or Data Rows – into the respective objects, also have the function to do validation which will be described later in this post.

Next, the DBField class which is required to do the actual mapping between the class property and the field name from the relational database:

1 /// <summary> 2 /// Custom attribute to hold the databse field name for a defined object property 3 /// </summary> 4 [AttributeUsage(AttributeTargets.Property)] 5 public class DbField : Attribute 6 { 7 /// <summary> 8 /// Gets or sets the name of the dbfield. 9 /// </summary> 10 /// <value> 11 /// The name of the dbfield. 12 /// </value> 13 public string DbfieldName { get; set; } 14 15 /// <summary> 16 /// Initializes a new instance of the <see cref="DbField"/> class. 17 /// </summary> 18 public DbField() 19 { 20 } 21 }

Last part of the mapping solution is the object itself which can be as the following:

1 /// <summary> 2 /// Represent the bank object 3 /// </summary> 4 public class Bank 5 { 6 /// <summary> 7 /// Gets or sets the identifier. 8 /// </summary> 9 /// <value> 10 /// The identifier. 11 /// </value> 12 [DbField(DbfieldName="BNK_MGR_ID")] 13 public Nullable<int> Id {get; set;} 14 15 /// <summary> 16 /// Gets or sets the name. 17 /// </summary> 18 /// <value> 19 /// The name. 20 /// </value> 21 [StringLengthValidator(1, 255, MessageTemplate = "???? ????? ??? ?????")] 22 [DbField(DbfieldName="BNK_NMA")] 23 public string Name { get; set; } 24 25 /// <summary> 26 /// Gets or sets the telephone. 27 /// </summary> 28 /// <value> 29 /// The telephone. 30 /// </value> 31 [DbField(DbfieldName="BNK_TEL")] 32 public string Telephone { get; set; } 33 34 /// <summary> 35 /// Gets or sets the fax. 36 /// </summary> 37 /// <value> 38 /// The fax. 39 /// </value> 40 [DbField(DbfieldName="BNK_FAX")] 41 public string Fax { get; set; } 42 43 /// <summary> 44 /// Gets or sets the email. 45 /// </summary> 46 /// <value> 47 /// The email. 48 /// </value> 49 [DbField(DbfieldName="BNK_EMAIL")] 50 public string Email { get; set; } 51 52 /// <summary> 53 /// Gets or sets the address. 54 /// </summary> 55 /// <value> 56 /// The address. 57 /// </value> 58 public string Address { get; set; } 59 /// <summary> 60 /// Gets or sets the note. 61 /// </summary> 62 /// <value> 63 /// The note. 64 /// </value> 65 [DbField(DbfieldName="BNK_NOTE")] 66 public string Note { get; set; } 67 68 /// <summary> 69 /// Initializes a new instance of the <see cref="Bank"/> class. 70 /// </summary> 71 public Bank() { } 72 }

As you can notice, DbField attribute is used to tell the adapter of the actual field name which comes from the data source.

Finally, the adapter itself to be created as the following:

1 /// <summary> 2 /// Bank adapter 3 /// </summary> 4 public class BankAdapter : AdapterBase<Bank> 5 { 6 /// <summary> 7 /// Gets the by identifier. 8 /// </summary> 9 /// <param name="id">The identifier.</param> 10 /// <returns></returns> 11 public static Bank GetById(int id) 12 { 13 return GetObject(BankRef.GeById(id).Tables[0].Rows[0]); 14 } 15 16 /// <summary> 17 /// Gets all. 18 /// </summary> 19 /// <returns></returns> 20 public static Collection<Bank> GetAll() 21 { 22 return GetCollection(BankRef.GetAll().Tables[0]); 23 } 24 25 /// <summary> 26 /// Adds the specified new bank. 27 /// </summary> 28 /// <param name="newBank">The new bank.</param> 29 /// <returns></returns> 30 public static string Add(Bank newBank) 31 { 32 return BankRef.Insert(newBank.Name, newBank.Telephone, newBank.Fax, newBank.Email, newBank.Address, newBank.Note); 33 } 34 35 /// <summary> 36 /// Updates the specified edited bank. 37 /// </summary> 38 /// <param name="editedBank">The edited bank.</param> 39 /// <returns></returns> 40 public static bool Update(Bank editedBank) 41 { 42 if (BankRef.Update(editedBank.Id.Value, editedBank.Name, editedBank.Telephone, editedBank.Fax, editedBank.Email, editedBank.Address, editedBank.Note) > 0) 43 return true; 44 else 45 return false; 46 } 47 48 /// <summary> 49 /// Gets all lite. 50 /// </summary> 51 /// <returns></returns> 52 public static Collection<Bank> GetAllLite() 53 { 54 return GetCollection(BankRef.GetAllLite().Tables[0]); 55 } 56 57 public static Collection<Bank> GetAllLiteForElevation() 58 { 59 return GetCollection(BankRef.GetAllLiteForElevation().Tables[0]); 60 } 61 62 }

You can notice the usage of the GetCollection and GetObject methods which is inherited from the base adapter class.

The solution can be used to teach starters the basics of ORM and the usage of Enterprise Library.

I hope that helped

Ahmed

Advertisements

One thought on “Using Enterprise Library to Map Data Into Objects (Simple ORM)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s