Skip to content

Instantly share code, notes, and snippets.

@stanroze
Created April 7, 2013 18:06
Show Gist options
  • Save stanroze/5331658 to your computer and use it in GitHub Desktop.
Save stanroze/5331658 to your computer and use it in GitHub Desktop.
Simple DB layer example, if not possible to use ORM or domain-driven design.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DbLayerSample
{
class Program
{
static void Main(string[] args)
{
Database dB = new Database();
dB.Query<InsertStudent>().Where(student => student.Name = "Stan").Execute();
Console.ReadLine();
}
}
public class Database
{
//ignoring how to get connection strings.
public Database<T> Query<T>() where T : IQuery, new() //
{
return new Database<T>("some connection string");
}
}
public class Database<T> where T : IQuery, new()
{
public string ConnectionString { get; private set; }
private readonly T query;
public Database(string connectionString)
{
this.ConnectionString = connectionString;
this.query = new T(); // <-- new() constraint allows me to it
}
public Database<T> Where(Action<T> filler)
{
filler(query);
return this;
}
public bool Execute()
{
Console.WriteLine("Execute: {0}", query.SqlCommandText);
return true;
}
}
public class InsertStudent : IQuery
{
public string Name { get; set; }
public string SqlCommandText
{
get
{
return string.Format("insert name = {0} into students", this.Name);
}
}
}
public interface IQuery
{
string SqlCommandText { get; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment