Click here to Skip to main content
6,822,613 members and growing! (19,501 online)
Email Password   helpLost your password?
Database » Database » Data Access     Intermediate License: The Code Project Open License (CPOL)

Easy Data Access Layer

By eng. Plamen Kovandjiev

This library gives an easy data access tool for different data sources.
C#2.0, C#3.0, .NET, ADO.NET, Dev
Revision:2 (See All)
Posted:20 Oct 2008
Updated:10 Mar 2009
Views:18,448
Bookmarked:72 times
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
15 votes for this article.
Popularity: 4.50 Rating: 3.82 out of 5
3 votes, 20.0%
1

2
2 votes, 13.3%
3
2 votes, 13.3%
4
8 votes, 53.3%
5

Introduction

This library gives an easy to use and unified access to different data sources. This library has providers for Microsoft SQL Server, Postgree, FireBird and MySQL, SQLite, Oracle, SqlServerCe and it is easy to add new ones. This library uses the following technologies and patterns:

  • Abstract Factory - for instantiation of the needed data sources
  • Generic Singleton - to get a single instance of a data source
  • LINQ - for transformation of data into a Generic List

The last one simplifies the implementation of the Entity Data Model (EDM).

Using the Code

Here is the hierarchy of the common classes:

Diagram.JPG

The entry point of the library is the DataLayer class. It uses the "Abstract Factory" pattern, and serves for the instantiation of objects that implement interfaces of type IDataLayer of the required types. The factory method of the DataLayer class is GetDataLayer, which can be used as follows:

  • Without parameters - Needed data for database types and connection string are obtained form the app.config of the library.
  • With parameter for database types - In this case, the connection string is obtained from app.config.
  • With parameters for database types and connection string.

From the GenericSingleton is obtained the needed instance for the connection to the database, and it is its responsibility to create only one instance from a given type.

The organization of the library: The interface IDataLayer describes the entire functionality. The abstract class DataLayerBase inherits IDataLayer and implements the base functionality for all data providers. When an instance of it is being created, it makes instances of common classes like DatabaseUtility, DBConnectionString, DBParameters for parsing and storing parameters and other classes. The idea of this class is to implement all the common functionality for the data providers; other methods which are specific for a data provider are abstract. The inheritor of the DataLayerBase class implements the abstract methods and creates a concrete connection object.

Configuration Settings

To create a layer from an app.config setting, add the following code:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="DataAccessLayer"
       type="System.Configuration.DictionarySectionHandler" />
  </configSections>

  <DataAccessLayer>
    <add key="ConnectionString"
       value="Server=localhost;User=SYSDBA;Password=masterkey;
              Database=D:\Catalog\trunk\DataBase\Catalog.fdb"/>
    <add key="DatabaseType" value="Firebird"/>
  </DataAccessLayer>
</configuration>

Here is an example of how the library can be used:

// Get data layer type from .config settings.
IDataLayer _dal = DataLayer.GetDataLayer();
// Get data layer following type
IDataLayer _dal = DataLayer.GetDataLayer(DatabaseType.MSSql,
   "Persist Security Info=True;Initial Catalog=pd_retrieval_frontend;" +
   "Data Source=SQLSERVER;User ID=sa;Password=strongPass;");

Example methods:

// Partial set SQL and Parameters.
_dal.Sql = "SELECT ID, Name FROM Employers WHERE ID > @ID";
_dal.Parameters.Add("ID", DbType.Int32, "10");
List<Employer> emp = _dal.ExecuteAndFillList<Employer>();

// Execute only SQL no parameters
List<Employer> emp = _dal.ExecuteAndFillList<Employer>(
                         "SELECT ID, Name FROM Employers");

// Execute SQL and Parameters lazy.
List<Employer> emp = _dal.ExecuteAndFillList<Employer>
	("SELECT ID, Name FROM Employers WHERE ID > @ID", 10);

The result is a list of a given type.

Other methods include:

  • ExecuteNonQuery(); - Execute a SQL with no return value. For DELETE, UPDATE, or INSERT statements.
  • ExecuteScalar(); - Execute a SQL and return only the first left cell from the table.
  • ExecuteDataTable(); - Execute a SQL and return a DataTable object.
  • ExecuteDataSet(); - Execute a SQL and return a DataSet object.
  • ExecuteDataReader(); - Execute a SQL and return a DataReader object.
  • ExecuteAndFillList<T>(); - Execute a SQL and fill List from the T entity.

Error Event Handler

To generate an error from the data layer, fire this error handler:

_dal.DatabaseError += new EventHandler<DatabaseErrorEventArgs>(DataLayer_DatabaseError);

The property RaisedError indicates if the previous operation raised an error.

Additional functionality: When the connection string is changed, the connection will be closed and reopened with actual data. When an Execute operation is invoked, a check is done to see if the connection is closed and an attempt made to establish a new connection without throwing an exception. If a connection cannot be established, an exception will be thrown. This exception can be processed and saved in LastError, or thrown again. When a new SQL command is applied, the previous parameters are cleaned.

Points of Interest

This library can be used while implementing an Entity Data Model (EDM) where we have the ability to use Stored Procedures and optimized queries for database requests.

History

The first implementation was only for Microsoft SQL Server, and later code was added for Postgree and Firebird. The major parts of the specific classes were moved to the base class. New execute void methods were added and a new event is fired if an exception is raised. Also added a new property RaisedError. New adds support for MySQL server.

Version 1.1

Support is added for the following servers: SQLite, Oracle, SqlServerCe. The usage of DataContext is removed which increased the performance with up to 20% when using ExecuteAndFillList methods. Other minor changes to the code. The default CommandType is set to Text. For every server implementation, for better handling of a broken connection, CheckConnBroken method is added. The library is 100% compatible with MONO.

License

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

About the Author

eng. Plamen Kovandjiev


Member

Occupation: Software Developer (Senior)
Company: Osceola EOOD
Location: Bulgaria Bulgaria

Other popular Database articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 11 of 11 (Total in Forum: 11) (Refresh)FirstPrevNext
GeneralExcellent Code.... PinmemberGary Noble5:13 9 Mar '09  
GeneralRe: Excellent Code.... Pinmembereng. Plamen Kovandjiev9:40 9 Mar '09  
GeneralSQL server compact Pinmemberaldo hexosa17:34 18 Dec '08  
GeneralRe: SQL server compact Pinmembereng. Plamen Kovandjiev6:26 20 Dec '08  
GeneralAny support for SQLite? Pinmembernji785:37 6 Dec '08  
NewsRe: Any support for SQLite? Pinmembereng. Plamen Kovandjiev4:01 7 Dec '08  
GeneralExcellent Pinmemberthund3rstruck10:50 5 Dec '08  
GeneralMySQL PinmemberMember 17809896:40 24 Nov '08  
GeneralRe: MySQL Pinmembereng. Plamen Kovandjiev8:24 24 Nov '08  
JokeRe: MySQL Pinmembereng. Plamen Kovandjiev3:55 7 Dec '08  
GeneralWhere's the code? PinmemberPIEBALDconsult6:43 20 Oct '08  

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

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

PermaLink | Privacy | Terms of Use
Last Updated: 10 Mar 2009
Editor: Deeksha Shenoy
Copyright 2008 by eng. Plamen Kovandjiev
Everything else Copyright © CodeProject, 1999-2010
Web10 | Advertise on the Code Project