Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » ADO.NET & Database » Generate SQL Statements with objects, Attributes and Reflection

Generate SQL Statements with objects, Attributes and Reflection

Create a SQL Command with SQL Statement and Parameters dynamically.

Technologies: .NET Compact Framework, .NET 1.0/1.1, ADO.NET, ADO.NET,Visual C# .NET
Total downloads :
Total page views :  14950
Rating :
 5/5
This article has been rated :  4 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
ArticleAd
Become a Sponsor



Introduction

Many developers hate one thing about software development, writing SQL Statements. SQL is a language on its own and it is ubiquitous in today's development environment. When there are changes made to the tables, we have to modify the affected SQL statements, be it in the application codes or in Stored Procedures.

Would it be good if we do not have to write or modify SQL statements, just modify some C# codes, compile and Voila, your application is good to go.

Can it be done?

Sure.

How?

We will be using Attributes that can be used on your objects to map the properties to a Database Table Column. And we will look into  Reflection classes to help us to create a simple SELECT Statement Command dynamically, with parameters and values assigned to the parameters.

Attributes

During development, we may have used attributes in our codes, one of the most commonly used attributes is the WebMethod attributes to expose methods in a web service. And who can forget about DllImport when calling Windows API.

For this solution, we will need to create a custom attribute object. To do that, we have to create a class and inherit the Attribute class.

public class DAOAttribute:System.Attribute

{
   
public DAOAttribute():base()
    {
    }
}


For this class, we need to declare 3 variables and exposed it through properties.

private string _DatabaseColumn;

private Type _ValueType;

private bool _PrimaryKey;

public string DatabaseColumn
{
    get
    {
       
return this._DatabaseColumn ;
    }
    
set
    {
        _DatabaseColumn =
value;
    }
}

public Type ValueType
{
    get
    {
        
return this._ValueType ;
    }
    
set
    {
        _ValueType =
value
    }
}

public bool PrimaryKey
{
    get
    {
       
return this._PrimaryKey ;
    }
    
set
    {
        _PrimaryKey =
value;
    }
}

 

  1.  _DatabaseColumn, this variable stores the database Column name
  2. _ValueType, this variable represents the Value Type
  3.  _PrimaryKey, indicates if the Database Column is a primary key

Next, we need to modify the Constructor to initialize the 3 variables

public DAOAttribute(string databaseColumn,Type valueType,bool primaryKey):base()
{
    _DatabaseColumn = databaseColumn;
    _ValueType = valueType;
    _PrimaryKey = primaryKey;

}


And we are ready to get to the next level.

Implementing the Attribute

Below is the code for the object that I will be using for this example

public class Customer

{

    private string _CustomerFirstName;

    private string _CustomerLastName;

    private string _CustomerIDNumber;

 

    public Customer()

    {

        _CustomerFirstName = "";

        _CustomerLastName = "";

        _CustomerIDNumber= "";

    }

 

    public string CustomerFirstName

    {

        get

        {

            return _CustomerFirstName;

        }

 

        set

        {

            _CustomerFirstName = value;

        }

    }

 

    public string CustomerLastName

    {

        get

        {

            return _CustomerLastName;

        }

 

        set

        {

            _CustomerLastName = value;

        }

    }

 

    public string CustomerIDNumber

    {

        get

        {

            return _CustomerIDNumber;

        }

 

        set

        {

            _CustomerIDNumber = value;

        }

    }

}

Assume you have an existing customer object that you want to generate SQL statement from. All you need now is to add in the attributes to the Get function of each property. Why put it at the GET function? This is because we will be using Reflection to extract the value. We will come to the Reflection Part later.

Below are the codes, you noticed that I set the Primary Key to True for
CustomerIDNumber. This means that I have determined that the Customer ID number in the database is the Primary Key. You can determine your own Primary Key(s) , it is advisable to follow the relevant Database Table that the object is representing. If there are no Primary Keys set for the Database Table, you can determine your own for this object.

public string CustomerFirstName

{

    [DAO("FirstName", typeof(string), false)]

 

    get

    {

        return _CustomerFirstName;

    }

 

    set

    {

        _CustomerFirstName = value;

    }

}

 

public string CustomerLastName

{

    [DAO("LastName", typeof(string), false)]

 

    get

    {

        return _CustomerLastName;

    }

 

    set

    {

        _CustomerLastName = value;

    }

}

 

public string CustomerIDNumber

{

    [DAO("CustID", typeof(string), true)]

 

    get

    {

        return _CustomerIDNumber;

    }

 

    set

    {

        _CustomerIDNumber = value;

    }

}

Executing it with Reflection

To retrieve the attributes from the object, we have to go deeper into the .NET framework. We are going to use classes in the Reflection namespace to extract the attribute details from the Customer object.  Below are the codes to create a generic DbCommand object with a Select Statement with Parameters in place.  

private DbCommand CreateSelectCommand(object dataObject,  DbProviderFactory factory, string TableName)

{

    Type t = dataObject.GetType();

    DAOAttribute dao;

    DbCommand cmd = factory.CreateCommand();

    DbParameter param;

 

    StringCollection Fields = new StringCollection();

    StringBuilder sbWhere = new StringBuilder(" WHERE ");

    bool HasCondition = false; //Indicates that there is a WHERE Condition

 

    foreach (System.Reflection.MethodInfo mi in t.GetMethods()) //Go thru each method of the object

    {

        foreach (Attribute att in Attribute.GetCustomAttributes(mi))  //Go thru the attributes for the method

        {

            if (typeof(DAOAttribute).IsAssignableFrom(att.GetType())) //Checks that the Attribute is of the right type

            {

                dao = (DAOAttribute)att;

                Fields.Add(dao.FieldName); //Append the Fields 

                
               
if (dao.PrimaryKey)

                {

                    //Append the Conditions

                    if (HasCondition) sbWhere.Append(" AND ");

                    sbWhere.AppendFormat("{0} = @{0}", dao.FieldName);

                    param = factory.CreateParameter();

                    param.ParameterName = "@" + dao.FieldName;

 

                    if (cmd.Parameters.IndexOf(param.ParameterName) == 0)

                    {

                        param.DbType = (DbType)Enum.Parse(typeof(DbType), dao.ValueType.Name);

                        cmd.Parameters.Add(param);

                        param.Value = mi.Invoke(obj, null);

                    }

 

                        HasCondition = true; //Set the HasCondition flag to true

                }

            }

        }

    }

 

    string[] arrField = new string[Fields.Count];

    Fields.CopyTo(arrField, 0);

    cmd.CommandText = "SELECT " + string.Join(",", arrField) + " FROM " + TableName + (HasCondition ? sbWhere.ToString() : " ");

    return cmd;

}

Beyond Select Statements

This is a very practical example of using Attributes and Reflection. You may even create your own Insert Statement Commands with these codes. And also you may want to extend the DAOAttribute object to cater to your requirements.

Besides generating SQL statements, there are a lot of cool stuff that you can do with Attributes and Reflection, you can even create your own XML Attributes and Formatter for the classes you created!!!


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Edmund H Smith
Edmund is a Tech Lead for .NET Development and he is currently based in Singapore. Edmund have been involved in .NET developement since 2002. He has vast exposure in the IT industry, involved in IT projects for Aviation, Finance,Logistics, Postal and Marketing companies. Some of the technolgy involved in the projects includes ASP.NET C#,VB6 and K2.NET .
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Boost the performance of your .NET applications
“ANTS Profiler took us straight to the specific areas of our code which were the cause of our performance issues." Terry Phillips, Sr. Developer, Harley-Davidson Dealer Systems. Download your free trial of ANTS Profiler.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
ArticleAd
Become a Sponsor
Latest Comments:
Subject Posted By Posted On
Brilliant article :) Simon6/12/2007
One question to your sourcecode, the line "Type t = obj.GetType();" is suppose to be "Type t = dataObject.GetType();" right?
Reply | Email | Delete | Modify | 
 
 
Re: Brilliant article :) Edmund H 6/12/2007

That is correct. Thanks for your feedback

Reply | Email | Delete | Modify | 
nice but...Joe6/13/2007
thanks for this article. just a bit of attention to detail: private string _CustomerLastName; and _CustomerLastName = ""; are repeated unnecessarily.
Reply | Email | Delete | Modify | 
Thanks for the Feedback! :-)Edmund H 6/15/2007
Thanks for the feedback. I have corrected some errors
Reply | Email | Delete | Modify | 
query builderBhuvaneshwari7/17/2007
Hi, Can any one send me the code for, generating the aql queries automatically by selecting the appropriate commands from the list and by selecting the servername and database name..... in C#.NEt Please anyone help me in coding this program
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved