Generic Data Layer Class

Programming 20 September 2007 | 0 Comments

This is part 2 in a series. Click here to read part 1 on XML serialization if you have not done so already.


The evolution of this implementation went something like this:

  1. The desire, as a purest, to test the theory of removing all logic from the database in an application
  2. This led to an obvious choice of using straight XML as a storage medium, as it stores no relationship information
  3. I then started creating datalayer classes for each entity – this worked well.
  4. I realized after some refactoring that this was almost entirely repetitive and no new custom methods were required for each new entity layer.
  5. I refactored the class to use generics (the <T> operator introduced in .Net 2.0, and the same concept that has existed for many, many years in C++ and other more established programming languages)
  6. Voila! A working, totally generic data layer was born! The class is so small that I have posted the entire contents below:
 using System; using System.Collections.Generic; using System.Configuration; using System.IO;
 using System.Text; using System.Xml; using TwentySeven.Framework.Data;
namespace TwentySeven.Framework.Data
{ // A generic XML persistor and retriever public class GenericData
{ #region Constructor // Initializes a new instance of the  class. public GenericData()
{ this.rootPath = Services.Default.XMLPath; }
#endregion #region Declarations private string rootPath;
private string extension = ".xml"; #endregion #region Methods // Saves the specified generic list.
public void Save(List genericList) { if (!File.Exists(rootPath + typeof(T).Name + extension))
{ FileStream fs = File.Create(rootPath + typeof(T).Name + extension); fs.Close(); }
StreamWriter writer = new StreamWriter(rootPath + typeof(T).Name + extension, false);
writer.Write(Manipulation.SerializeObjectToXML(genericList)); writer.Close(); }
// Gets this instance. public List Get() { List genericList = new List();
if (File.Exists(rootPath + typeof(T).Name + extension))
{ StreamReader reader = new StreamReader(rootPath + typeof(T).Name + extension);
genericList.AddRange((List)Manipulation.LoadObjectFromXML(reader.ReadToEnd(), typeof(List)));
reader.Close(); } return genericList; } #endregion } }

A couple of notes you should understand:

  1. The Manipulation class is just a reference to my Framework class that contains the XML serialization code discussed in part 1.
  2. All data is persisted and retrieved as lists. This means that for each entity you define and require, a single XML file will be created.
  3. There are only 2 methods: Get and Set Hawt stuff indeed.

Is this powerful enough for an enterprise application? Could it be this simple? As it turns out, so far the answer appears to be YES!

My next post will deal with using this generic data class to actually do some meaningful work when called from a generic business class.

Leave a Reply