In this short example I will demonstrate a powerful feature of Reflection that will allow you to dynamically set the values of a class. By setting the properties of a class dynamically, you can create a simple method that allows your class to be constructed and pre-populated from a database.
We will use an Employee class, and a stored procedure named getAllEmployees.
The stored procedure looks like this:
CREATE PROCEDURE
dbo.getAllEmployeesAS
select * from employees
RETURN The procedure above will get all the employee records from the Employees table. Create this stored procedure in your Northwind database. (Installed by default with SQL server installation)
public class EmployeeCollection
{
#region Start - private variables
private int _employeeID;
private string _lastName;
private string _firstName;
#endregion
public EmployeeCollection(){}
public int EmployeeID
{
get { return _employeeID; }
set { _employeeID = value; }
}
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
}
The Employee class contains a subset of properties that correspond to the column names of the Employees table. We will now create a new constructor for the Employee class. This constructor will allow us to perform some magic. The constructor will accept a DataRow as a parameter. When the constructor is called it will set the properties of the Employee class based on the data in the DataRow parameter. By doing this, you will be able to construct a collection of employees in a very simple manner.
satyen mishraPosted Mar 3, 2022, 9:58 AM
Hello David, very nice article, Can I ask the following ?: I have a database configurable data stored in a table called dbo.CONFIG. This stores basically all the confKey and its confValues. It was just 2 columns in it. My question would How can I just call or hit once to the dbo.CONFIG table, bring all the confKeys and confValues records, store it in a class object session and then utilize the sessions attributes across all the pages as and when required. Is this approach looks correct or What would be your way. My purpose is to just call once to the CONFIG table i.e. hitting once to the DB and then perform in application session to improve performance.