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
{
[EntityDescription("Name")]
public string Name;

[EntityDescription("Phone")]
public String Phone;
}

//Entity; Entities Inside=1
public class Addresses : BaseEntity
{
[EntityDescription("Name")]
public string Name;

[EntityDescription("Number")]
public Int32 Number;

[EntityDescription("Contact")]
public Contacts Contact;
}

//Entity; Entities Inside=1.1
public class Models : BaseEntity
{
[EntityDescription("Name")]
public String Name;

[EntityDescription("Age")]
public Int32 Age;

[EntityDescription("Address")]
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
{
//Dummies
List<KeyValuePair<String, object>> ret = new List<KeyValuePair<string, object>>();
string description = String.Empty; object val = null; bool isbase;

//List of EntityDescripted Fields
input.GetType().GetFields().Where
(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.

Advertisements

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