Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

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

0.00/5 (No votes)
20 Mar 2002 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.

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:

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:

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