Demonstrating Attributes and Reflection in .NET - Attributes Applied (Page 4 of 8 )
Now that we have defined our custom attributes, let's look at a sample class that uses these attributes to specify how a class maps to a table within a database. The Student class below shows the above custom attributes in action.
[DBTable("Student", "dbo")] class Student { private string _id; // id of the student private string _firstName; // first name private string _lastName; // last name private string _address; // address private int _numCourses; // number of courses
/// /// The ID of the student /// /// // the student id is the primary key and identifies // a unique row [DBPrimaryKeyField("StudentID", DbType.String)] [DBColumn("student_id", DbType.Guid, false)] public string ID { get { return _id; } set { _id = value; } } /// /// the first name of the student /// [DBColumn("first_name", DbType.String, false)] public string FirstName { get { return _firstName; } set { _firstName = value; } } /// /// the last name of the student /// [DBColumn("last_name", DbType.String, false)] public string LastName { get { return _lastName; } set { _lastName = value; } } /// /// the address of the student /// [DBColumn("address", DbType.String, true)] public string Address { get { return _address; } set { _address = value; } } /// /// the number of courses the student is enrolled in /// [DBColumn("num_courses", DbType.Int32, true)] public int NumberOfCourses { get { return _numCourses; } set { _numCourses = value; } } }
In the code above, we provide meta-data that indicates: 1) the table name that the Student class should persist rows to (Student in this example), 2) the attributes that indicate a unique row (there is only one key field called StudentID), and 3) the column names that the properties should map to (student_id, first_name, last_name, and address, respectively).
Let's look at some code that uses this metadata (i.e. the custom attributes) in a meaningful way. In the next sections we will write C# code using .NET reflection to generate SQL statements for a particular object.
The class generating these SQL statements will be called SqlGenerator. We will also design an SqlObjectManager class that exposes a simple interface for managing objects in a SQL server database. The class diagram for these two classes is shown below: