Use properties and reflection transition from data access layer to business objects - ii

xiaoxiao2021-03-06  69

Introduction

In the previous article, I introduced the use of Attributes to describe business objects. This article I will show how to extract the description from the class. To explain how it works, I will write an application through the ATtributes used in the class. Creating a SQL script is used to generate a table.

tool

This is a console application. Tools will load the accessory, enumerate that the category is a DataTable Attibute generated SQL script to create a table.

Start loading part of the code:

Public static void main (string [] args)

{

IF (args.length! = 1)

{

Console.Writeline ("Usage: Scriptgen [Assembly Path]");

Return;

}

AskEMBLY Assembly = NULL;

Try

{

askMBLY = askFROMBLY.LOADFROM (args [0]);

}

Catch (Exception E)

{

Console.WriteLine ("Failed to Load Assembly");

Console.writeLine (E.MESSAGE);

}

}

The above code is attempting to load the accessory through the parameter path. Now we must list all the accessories containing the DataTable Attribute. In order to complete this job, please see the following code:

Public void Parseassembly (askSEMBLY Assembly)

{

TYPE [] TYPES = askES ();

FOREACH (Type Type ")

{

IF (Type.Isclass)

{

DataTableAttribute [] dataable = (DataTableAttribute [])

Type.getCustomattributes (TypeOf (DataTableAttribute),

True);

IF (DataTable.Length> 0)

{

Console.writeline ("Found Class '{0}'", TYPE.TOSTRING ());

}

}

}

}

The following is a code that enumerate attributes.

Void PaSeclass (Type Type, DataTableAttribute DataTable)

{

PropertyInfo [] Properties = type.getproperties ();

// Gets the key field

Foreach (PropertyInfo Property In Properties)

{

KeyfieldaTribute [] key = (keyfieldattribute [])

Property.getCustomAttributes (TypeF (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)

{

Basefieldtattribute [] Field = (Basefieldattribute [])

Property.getCustomattributes (TypeF (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 we have to create a SQL script. Our tools can only meet 2 needs: key is int, the Identify property type is only allowed: string, int, decimal, and datetime.

Source files will create the following assemblies:

Dal.dll: Contains Attributes

Customer.dll: Contains business objects

Scriptgen.exe: Tools used to generate SQL scripts.

Next step

Next article I will create the entire DAL to get objects at runtime.

转载请注明原文地址:https://www.9cbs.com/read-90892.html

New Post(0)