Click here to Skip to main content
6,635,160 members and growing! (15,861 online)
Email Password   helpLost your password?
Languages » C# » Generics     Intermediate License: The Code Project Open License (CPOL)

An Easy Way to Populate Instances using Generics

By Martin Olivares

A sample of using generics to simplify a Data Access Layer
C# 2.0, Windows, .NET 2.0VS2005, Dev
Posted:20 Dec 2006
Views:17,023
Bookmarked:15 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
16 votes for this article.
Popularity: 3.76 Rating: 3.13 out of 5
3 votes, 18.8%
1
2 votes, 12.5%
2

3
2 votes, 12.5%
4
9 votes, 56.3%
5
Sample image

Introduction

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)

Background

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:

/// <SUMMARY>
/// 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 = 
                   type.GetProperty(record.GetName(i), 
                   BindingFlags.IgnoreCase | 
                   BindingFlags.Public | BindingFlags.Instance);
                if (property != null)
                {
                    property.SetValue(entity, 
                           record[property.Name], null);
                }
            }
        }
    }
}

To fill an instance List:

/// <SUMMARY>
/// Populates a List of entities of type T.
/// </SUMMARY>
/// <PARAM name="dr">The DataReader with data of entities.</PARAM>
/// <RETURNS></RETURNS>
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);
        entities.Add(ent);
    }
    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.

Conclusion

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.

History

  • 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.

License

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

About the Author

Martin Olivares


Member
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#)


Occupation: Web Developer
Location: Argentina Argentina

Other popular C# articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 10 of 10 (Total in Forum: 10) (Refresh)FirstPrevNext
GeneralMaking it less error prone PinmemberCybernate6:47 9 Mar '09  
GeneralHandling Nulls Pinmembermdunn68:35 24 Jan '07  
AnswerRe: Handling Nulls PinmemberMartin Olivares10:03 24 Jan '07  
Generalusing ORMs with generics Pinmemberalejo_rybak2:39 22 Dec '06  
GeneralUsing Reflection problem PinmemberFireWorm23:14 20 Dec '06  
GeneralRe: Using Reflection problem PinmemberFireWorm23:26 20 Dec '06  
GeneralRe: Using Reflection problem PinmemberMartin Olivares12:37 21 Dec '06  
GeneralRe: Using Reflection problem Pinmembermeteorbites21:56 3 Jan '07  
GeneralRe: Using Reflection problem PinmemberSteve Mitcham9:02 4 Jan '07  
GeneralRe: Using Reflection problem PinmemberUL-Tomten8:48 29 Jul '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 20 Dec 2006
Editor: Deeksha Shenoy
Copyright 2006 by Martin Olivares
Everything else Copyright © CodeProject, 1999-2009
Web20 | Advertise on the Code Project