Click here to Skip to main content
15,880,796 members
Articles / Programming Languages / C#
Article

A Data Access Layer to persist business objects using attributes and reflection - Part II

Rate me:
Please Sign up or sign in to vote.
4.56/5 (11 votes)
20 Mar 20022 min read 100K   1.3K   95   1
Persistance to business objects through attributes and reflection

Index

Introduction

In the early article I introduced the attributes used to describe a business object. In this article I'll show how to extract this descriptive information from classes. To explain how it will be done I'll write an application that creates a SQL script to create tables according to the attributes applied used in the class.

The Tool

It will be a console application. As argument you pass the assembly name. The tool will load the assembly, enumerate the classes that are marked with the DataTable attribute and will generate the sql script to create the table.

We'll start with the code to load an assembly.

C#
public static void Main(string[] args)
{
    if (args.Length != 1)
    {
        Console.WriteLine("Usage: scriptgen [assembly path]");
        return;
    }


    Assembly assembly = null;

    try
    {
        assembly = Assembly.LoadFrom(args[0]);
    }
    catch (Exception e)
    {
        Console.WriteLine("Failed to load assembly [" + args[0] + "]");
        Console.WriteLine(e.Message);
    }

}

The code above tries to load the assembly according to the path in the argument. Now we must enumerate all of the assembly classes that have the DataTable attribute. To accomplish this take a look at the code below:

C#
public void ParseAssembly(Assembly assembly)
{
    Type[] types = assembly.GetTypes();

    foreach(Type type in types)
    {
        if (type.IsClass)
        {
            DataTableAttribute[] dataTable = (DataTableAttribute[]) 
                         type.GetCustomAttributes(typeof(DataTableAttribute), 
                                                  true);

            if (dataTable.Length > 0)
            {
                Console.WriteLine("Found class '{0}'", type.ToString());
            }
        }
    }
}

The code above gets all the types from the assembly, then checks if it's a class and if it has the DataTable attribute. If so it outputs the class name. We need to get all the properties that should be mapped to table columns. That's exactly what the code below does:

C#
void ParseClass(Type type, DataTableAttribute dataTable)
{
    PropertyInfo[] properties = type.GetProperties();

    // gets the key field
    foreach (PropertyInfo property in properties)
    {
        KeyFieldAttribute[] key = (KeyFieldAttribute[])
                       property.GetCustomAttributes(typeof(KeyFieldAttribute),
                                                    true);

        if (key.Length > 0)
        {
            Console.WriteLine("Key = " + property.Name + " type is "
                        + property.PropertyType);
            break;
        }
    }

    // gets the other fields
    foreach (PropertyInfo property in properties)
    {
        BaseFieldAttribute[] field = (BaseFieldAttribute[])
                      property.GetCustomAttributes(typeof(BaseFieldAttribute),
                                                   true);

        if (field.Length > 0)
        {
            if (!(field[0] is KeyFieldAttribute))
            {
                Console.WriteLine("Property " + property.Name
                                + " [" + property.PropertyType + "] " +
                                + "maps to column [
                                + field[0].ColumnName + "]");
            }

        }
    }
}

Now all we have to do is to create the sql script. Our tool in this version will only be able to create scripts that follow this 2 requisites: The key is a int, IDENTITY The property types allowed are: string, int, decimal and DateTime.

The source files included here will create the following assemblies:

  • DAL.dll: contains the attributes
  • Customer.dll: contains the business objects
  • scriptGen.exe: the tool that generates the sql script

Coming up next

In the next article I'll create the full DAL that gets an object in runtime and persists it in a database, as well as gets it from the data provider.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Architect VisionOne AG
Switzerland Switzerland
XicoLoko is a brazilian developer based in Switzerland.

Comments and Discussions

 
GeneralAlberto García Pin
AlbertoGarciaArdiles8-Mar-04 7:24
AlbertoGarciaArdiles8-Mar-04 7:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.