kian ryan - code, photography, bob » Page 'A Simple Generic Repository for Linq to SQL'

A Simple Generic Repository for Linq to SQL

Two code posts in one day, aren’t you lot lucky?

I’m currently working on a small project working with Microsoft ASP.NET MVC. I admit I’m rather enjoying the experience, it’s nice to get back to proper bare metal GETs and POSTs with non of the fluff of normal ASP.NET getting in the way. Since this is a relatively simple project I’m using Linq to SQL rather than the Entity framework. Whilst putting some boilerplate code together (after following the excellent NerdDinner tutorial) I realised there was a lack of a simple generic repository for common object operations. So I present to you my basic, generic repository:

using System.Data.Linq.Mapping;
using System.Linq;
using System.Linq.Expressions;
using BrandingScience.Models;
using System;</p>

<p>public abstract class Repository<T, C> where T : class where C : System.Data.Linq.DataContext, new()
{
    private C db = new C();</p>

<pre><code>// Query Methods
public IQueryable&lt;T&gt; FindAll()
{
    return db.GetTable&lt;T&gt;();
}


public T Get(int id)
{
    MetaTable mapping = db.Mapping.GetTable(typeof(T));
    MetaDataMember pkfield = mapping.RowType.DataMembers.SingleOrDefault(d =&gt; d.IsPrimaryKey);

    ParameterExpression param = Expression.Parameter(typeof(T), "e");
    var p = Expression.Lambda&lt;Func&lt;T, bool&gt;&gt;(
          Expression.Equal(Expression.Property(param, pkfield.Name),
          Expression.Constant(id)),
          new ParameterExpression[] { param });

    return db.GetTable&lt;T&gt;().SingleOrDefault(p);

}

// Insert/Delete
public void Add(T t)
{
    db.GetTable&lt;T&gt;().InsertOnSubmit(t);
}

public void Delete(T t)
{
    db.GetTable&lt;T&gt;().DeleteOnSubmit(t);
}

// Persistence
public void Save()
{
    db.SubmitChanges();
}
</code></pre>

<p>}

T is the table class you want to create the repository for, C is the DataContext created by Linq to SQL. Pretty straightforward. A typical implementation looks like this:

public class JobRepository : Repository<Job, MyDataContext>
{
}</p>

<p>public static void Main(string[] args)
{
    JobRepository jobRepository = new JobRepository();
    List<Job> allJobs = jobRepository.FindAll();</p>

<pre><code>// Return a single item and change the title.
Job job = jobRepository.Get(1);
job.Title = "Mutated Gerkhin Production";

// Create a new item.
Job newJob = new Job();
newJob.Title = "Mutated Gerkhin Anti-Coagulant Production";
jobRepository.Add(newJob);

// Delete an old item.
Job removeJob = jobRepository.Get(2);
Console.WriteLine(removeJob.Title); // Output: Survival of human race.
jobRepository.Delete(removeJob);

// Save all changes to the repository.
jobRepository.Save();
</code></pre>

<p>}

This version currently does not support dependancy injection, which is something I’ll be looking into shortly. But for now, it saves a heck of a lot of time to just get the simple stuff done. I’m surprised MS didn’t actually ship Linq to SQL with something similar.

2 comments to “A Simple Generic Repository for Linq to SQL”

  1. Perfect, thanks – exactly was I was looking for :)

  2. I’m glad to hear it :-) I’ll likely be posting an update in a week – it’s had some tweaks as I’ve continued to use it, so check back here.

Leave a comment

XHTML - You can use:<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

© 2008 kian ryan – code, photography, bob is powered by WordPress

Bad Behavior has blocked 34 access attempts in the last 7 days.