Click here to Skip to main content
Click here to Skip to main content

An Easy Way to Populate Instances using Generics

, 20 Dec 2006 CPOL
Rate this:
Please Sign up or sign in to vote.
A sample of using generics to simplify a Data Access Layer
Sample image


With the insertion of Generics in the 2.0 Framework, developers have a tool that radically changes the way to develop. Some of the main advantages of using Generics are:

  • Type Safety
  • Intellisense support
  • Reduction of repetitive code
  • Collections with great functionality included (Collections, List, Queue, Stack, LinkedList)


In almost all applications, it's necessary to persist the state of the instances of the objects that we use soon to be consulted and to regenerate these instances. This process of regeneration generally implies great amount of code, nontyped collections, that result in error sensible code and smaller performance. In this simplified example of a data access layer, we will see that it is possible to obtain an instance or list of instances of any entity with only two generic methods.

Generics Methods

To fill one instance:

/// Populates an instance of the entity.
/// </SUMMARY>
/// <PARAM name="entity">The instance of the entity to populate.</PARAM>
/// <PARAM name="record">The current Datareader record.</PARAM>
public static void PopulateEntity<T>(T entity, IDataRecord record)
    if (record != null && record.FieldCount > 0)
        Type type = entity.GetType();

        for (int i = 0; i < record.FieldCount; i++)
            if (DBNull.Value != record[i])
                PropertyInfo property = 
                   BindingFlags.IgnoreCase | 
                   BindingFlags.Public | BindingFlags.Instance);
                if (property != null)
                           record[property.Name], null);

To fill an instance List:

/// Populates a List of entities of type T.
/// </SUMMARY>
/// <PARAM name="dr">The DataReader with data of entities.</PARAM>
public static List<T> PopulateEntities<T>(IDataReader dr)
    List<T> entities = new List<T>();
    while (dr.Read())
        T ent = Activator.CreateInstance<T>();
        PopulateEntity<T>(ent, dr);
    return entities;

Using the Methods

If we need a single instance of one entity, invoke the method PopulateEntity passing as parameter the entity type, an empty instance and a record of a Datareader.

public static Contact getContactById(int id)
    Contact contact = new Contact();
    Database db = DatabaseFactory.CreateDatabase();
    DbCommand dbCommand = db.GetStoredProcCommand("ContactById");
    db.AddInParameter(dbCommand, "contactId", DbType.Int32, id);
    IDataReader idr = db.ExecuteReader(dbCommand);
    if (idr.Read())
        EntityUtils.PopulateEntity<Contact>(contact, idr);
    return contact;

If we need an instance collection of one entity, invoke the method PopulateEntities passing as parameter the entity type and Datareader.

public static List<Contact> getContacts()
    Database db = DatabaseFactory.CreateDatabase();
    DbCommand dbCommand = db.GetStoredProcCommand("ContactGetAll");
    IDataReader idr = db.ExecuteReader(dbCommand);
    return (EntityUtils.PopulateEntities<Contact>(idr));

Using generics List as return of PopulateEntities we have an instance collection with methods having great functionality to sort, find, iterate, manage in our business and user interface layers.

Configure the Sample Project

The sample uses the AdventureWorks database included in SQL Server 2005. Modify the connection string LocalSqlServer located in web.config and run the script StoredProcedures.sql located in the App_Data directory to add the necessary stored procedures.


The inclusion of Generics in the Framework produced a jump of maturity and productivity to this tool. Therefore I consider that is one of the aspects in which it is necessary to deepen knowledge, otherwise we will lose an easy and advantageous way to develop.


  • 20th December, 2006: Initial post

About Martín Olivares

I'm an system engineer with 8 years of experience as a developer/architect in enterprise project solutions. I have always worked with Microsoft Platforms and technologies such as VB, SQL Server, .NET, MSF.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Martin Olivares
Web Developer
Argentina Argentina
I'm an system engineer with 8 years of experience as developer/architect in enterprise web development using MS technologies (Asp.Net, Ajax, Sql Server, C#)

Comments and Discussions

GeneralMaking it less error prone PinmemberCybernate9-Mar-09 6:47 
GeneralHandling Nulls Pinmembermdunn624-Jan-07 8:35 
AnswerRe: Handling Nulls PinmemberMartin Olivares24-Jan-07 10:03 
Generalusing ORMs with generics Pinmemberalejo_rybak22-Dec-06 2:39 
GeneralUsing Reflection problem PinmemberFireWorm20-Dec-06 23:14 
GeneralRe: Using Reflection problem PinmemberFireWorm20-Dec-06 23:26 
GeneralRe: Using Reflection problem PinmemberMartin Olivares21-Dec-06 12:37 
GeneralRe: Using Reflection problem Pinmembermeteorbites3-Jan-07 21:56 
GeneralRe: Using Reflection problem PinmemberSteve Mitcham4-Jan-07 9:02 
GeneralRe: Using Reflection problem PinmemberUL-Tomten29-Jul-07 8:48 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150305.1 | Last Updated 20 Dec 2006
Article Copyright 2006 by Martin Olivares
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid