Automating the Data Access [1]

Previously we defined the BaseEntity and the EntityDescriptionAttribute, now we can use them in classes to create our database structure. For the first view let’s create three classes:

//Primitive Entity; Entities Inside=0
public class Contacts : BaseEntity
public string Name;

public String Phone;

//Entity; Entities Inside=1
public class Addresses : BaseEntity
public string Name;

public Int32 Number;

public Contacts Contact;

//Entity; Entities Inside=1.1
public class Models : BaseEntity
public String Name;

public Int32 Age;

public Addresses Address;

Now we create the EntityParser to get the entityfield names and its values:

public static List> EntityParse(this T input) where T : BaseEntity
List<KeyValuePair<String, object>> ret = new List<KeyValuePair<string, object>>();
string description = String.Empty; object val = null; bool isbase;

//List of EntityDescripted Fields
(w => w.GetCustomAttributes(typeof(EntityDescriptionAttribute),false).Length > 0).ToList().ForEach(f=>
val = f.GetValue(input);
isbase = f.FieldType.BaseType == typeof(BaseEntity); // The value is another Entity

if (isbase)
val = EntityParse(val as BaseEntity); //The value is a List

//EntityDescription plus ID in case of Entity
description = (f.GetCustomAttributes(typeof(EntityDescriptionAttribute), false).
First() as EntityDescriptionAttribute).Description.ToUpper() + (isbase ? "ID" : "");

ret.Add(new KeyValuePair<string, object>(description, val));

return ret;

Our first test is creating an instance of Model and Parse it:

Contacts c = new Contacts() { Name = "John", Phone = "045" };
Addresses ad = new Addresses() { Name = "C/N", Number = 20, Contact = c };
Models m = new Models() { Age = 20, Name = "JP", Address = ad  };
var r = m.EntityParse();

And we will have ordered information to use it for creating tables and  inserting, selecting, and updating information.


Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s