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

Data Access Layer Auto Generation Library

By , 17 Dec 2008
 

Introduction

Data Access Layer (DAL) is an important part in almost all architectures. I encountered problems creating DAL for large databases — maintaining DAL for these databases was another nightmare. So I thought of a generic solution to this problem, which was to auto generate the DAL.

I made use of System.CodeDom which is a code generator to produce source code in a particular programming language.

Using the Code

In order to generate DAL in your ASP.NET project follow the below steps:

  1. Add a reference of DalProvider.dll which is a DAL Auto-Generator Library
  2. Add the following under compilation tag in the web.config
            <system.web>
    
    		<compilation debug="true">
    
    			<buildProviders>
    				 <add extension=".dal"
                                             type="AnoopsDALGenerator.DalProvider"/>
                    	<buildProviders>
     		</compilation>
    	</system.web>

    This allows the compilation of any file with the ".dal" extension added to the project with our DAL auto generation library.

  3. Add a XML file to the App_Code folder in the below mentioned format with the extension ".dal"
    	<dal>
       		<connectionString>Data Source =XXXXX; Initial Catalog = XXXXX;
                          User Id =XXXXX; Password=XXXXX 
    		</connectionString>
       		<nameSpace>DAL1</nameSpace>
    
    	</dal>

    In this XML file under the "dal" root tag we need to mention the connection string of the database as well as the namespace to access the auto generated DAL.

  4. Compile your ASP.NET project. This generates the DAL with the following features:
  • Namespace "DAL1" as specified in the XML file
  • All tables are represented as classes with its columns as member fields that can be accessed using property with name in the following pattern "Col" + Column Name. This enables the users to create objects of tables.
                DAL1.TableName table1 = new DAL1.TableName();
                tabel1.ColColumnName1 = "2";
                table2.ColColumnName2 = "Trial";
                Response.Write ("Data in column2:" +  table2.ColColumnName2);
  • All stored procedure access methods are defined under the DataProcedure class. Thus to access a stored procedure the user has to use the respective stored procedure access function ("Access"+StoredProcedureName).
                DAL2.DataProcedure dbObject = new DAL2.DataProcedure();
    	    DataTable dataResult=new DataTable();
                int returnStatus = dbObject.AccessStoredProcedureName(ref dataResult,
                    "21", "Thomas", "Atlas", "ITDept");
                if (returnStatus>

A reference to a datatable has to be passed to this function to retrieve the records fetched using the stored procedure.

Code

The code is big but simple. The work flow of this library is as below:

  • Extract the connection string and the proposed namespace from the XML file during compilation
  • Query the systemobjects table and systemcolumns table to list out the tables and columns respectively
                 --To extract the table information from database	            
                   Select * from sysobjects where type = 'u'
                 --To extract the column information with respect to the table 
    	      Select * from syscolumns
  • Generate classes from the table names and create coulmns as member variables under it
  • Create a class named DataProcedure to hold the functions to access stored procedures
  • Query the systemobjects table to list all the stored procedures
           Select * from sysobjects where type = 'p' and category = 0
  • Query systemcolumns to get the parameters of the respective stored procedure
  • SELECT
    param.name AS [Name],
    ISNULL(baset.name, N'') AS [SystemType],
    CAST(CASE WHEN baset.name IN (N'char', N'varchar', N'binary', N'varbinary',
        N'nchar', N'nvarchar') 
    THEN param.prec ELSE param.length END AS int) AS [Length],
    CAST(param.xprec AS int) AS [NumericPrecision],
    CAST(param.xscale AS int) AS [NumericScale],
    null AS [DefaultValue],
    CAST(
        CASE param.isoutparam WHEN 1 THEN param.isoutparam WHEN 0 THEN 
           CASE param.name WHEN '' 
    THEN 1 ELSE 0 END END AS bit) AS [IsOutputParameter]
    FROM
    dbo.sysobjects AS sp
    INNER JOIN sysusers AS ssp ON ssp.uid = sp.uid
    INNER JOIN syscolumns AS param ON (param.number = 1) AND (param.id=sp.id)
    LEFT OUTER JOIN systypes AS baset ON baset.xusertype = 
        param.xtype and baset.xusertype = baset.xtype
    WHERE
     (sp.xtype = N'P' OR sp.xtype = N'RF')and(sp.id= ?  and ssp.name=N'dbo')
    ORDER BY
    CAST(param.colid AS int) ASC
  • Combine all the information and generate functions to access stored procedures

Points of Interest

This solution is a good example of using System.CodeDom.

License

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

About the Author

Anoop Unnikrishnan
Software Developer
India India
Member
Anoop Unnikrishnan is associated with a CMM Level 5 Company. He has done his Bachelor of Engineering in Information Science. His certifications include OCA,IBM SOA Associate, MCAD, MCTS and MCPD. Currently persuing MBA.
 
He is working on .NET since first Beta versions. He has also published his book "Start Programming with C#".
 
Grab a copy from www.pothi.com/pothi/book/anoop-unnikrishnan-start-programming-c
 
Anoop can be reached : anoopukrish@gmail.com

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionDAL file has not createdmemberprabhu.d16 May '13 - 2:46 
Hi Anoop,
 
I have successfully compiled the application but the DAL file is not created,
 
Please tell me how to check it
 
Thanks & Regards,
Prabhu D
GeneralLibrary has trouble with tablenames using special charsmemberThomas-H.13 Jan '09 - 23:32 
My database has a table named T$OBJECTS for example. The generator tries to create a class called T$OBJECTS which fails throwing a compiler error CS1056.
 
I guess this is also happening on column names like C$COLUMN1.
 
Did not look into the code yet, just tried running it once, so I might find a solution for this.
 
Thanks for the article. The idea and solution looks fine so far.
GeneralRe: Library has trouble with tablenames using special charsmemberAnoop Unnikrishnan11 Mar '09 - 1:46 
Thanks for the appreciation. This is a new issue and probably you could alter the code and mask the special characters while creating classes and variables. However I will include the solution in the next release.
 
Thanks & Regards,
Anoop
GeneralObject reference not set to an instance of an object.memberPeter de Witte (wrk)22 Dec '08 - 21:54 
Keep getting this message when I try to build de example project.
 
System.NullReferenceException was unhandled by user code
Message="De objectverwijzing is niet op een exemplaar van een object ingesteld."
Source="DalProvider"
StackTrace:
bij AnoopsDALGenerator.DalLib.GenerateDalClasses(String inputFileName, Boolean isVirtualInputFile) in C:\Documents and Settings\anoop_u.THBS\Desktop\test\1\DalBuildProvider\DalGenLib.cs:regel 189
bij AnoopsDALGenerator.DalProvider.GenerateCode(AssemblyBuilder aBter) in C:\Documents and Settings\anoop_u.THBS\Desktop\test\1\DalBuildProvider\DalProvider.cs:regel 23
bij System.Web.Compilation.AssemblyBuilder.AddBuildProvider(BuildProvider buildProvider)
 
Can you determine why?
 
Peter de Witte

GeneralRe: Object reference not set to an instance of an object.memberAnoop Unnikrishnan25 Dec '08 - 23:10 
Try building the Dll first--> then remove the old reference in the ASP.NET project--> Add the new reference to the Dll-->Compile the ASP.Net project-->Check if the .dal file has a valid data source
 
Regards
Anoop
GeneralExcellent ArticlememberThomas C.P20 Dec '08 - 0:55 
Anoop.. This ia an excellent piece of work. I would like some more changes and auto intelligence to be part of this library. Could you pls help me out. Smile | :)
GeneralRe: Excellent ArticlememberAnoop Unnikrishnan20 Dec '08 - 19:41 
Sure please mail me the changes.
GeneralMy vote of 1memberRuchit Surati18 Dec '08 - 18:51 
no self inputs.
GeneralRe: My vote of 1memberAnoop Unnikrishnan20 Dec '08 - 19:44 
Pls make your statement clear. Will do the necessary.
 
Thanks & Regards,
Anoop
Questioncan work on MS Access?memberguaike17 Dec '08 - 19:17 
hi,Can this DAL lib work on MS Access?or anything else
AnswerRe: can work on MS Access?memberThomas C.P20 Dec '08 - 0:39 
Its coded for SQL Server. Please download the code to get a better idea, so that u could customise as per ur needs.
 
Regards,
Thomas
GeneralMy vote of 1member[DK]KiloDunse16 Dec '08 - 10:13 
Where is the article?
GeneralRe: My vote of 1 [modified]memberAnoop Unnikrishnan16 Dec '08 - 18:46 
As its a lengthy peace of code I couldnt include the explanations in the article. So in my next update i will try to include the work flow.
 
Thanks for your valuable feedback.
 
Cheers,
Anoop
 
modified on Monday, June 8, 2009 12:16 AM

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 17 Dec 2008
Article Copyright 2008 by Anoop Unnikrishnan
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid