IRepository

As I'm testing features of ASP.NET MVC, I'm noticing that it would  be really nice to be able perform non-persistent CRUD operations on POCO's.  Meaning, i need data, i need objects, but I don't want to set up a test database for these tests. I need to be able to create a class, and then create lists of instances of that class, and then add new ones, edit existing ones, delete some, exactly the same stuff I'd normally do, just no database. 

I searched on "IRepository" and came back with awesome examples, most of which enabled you to do almost if not everything you would need to do in your app, many of which I'll be revisiting.  But I couldn't find one that did almost nothing.  So I wrote one.  And it does...well, almost nothing.

Here is my initial version of IRepository:

public interface IRepository
			where TModel : IModel, new()

	TModel Find(int id);
	IEnumerable FindAll();
	void Save(TModel model);
	void Delete(TModel model);
	int Count { get; }
}
1
2
3
4
5
6
7
8
9

It's pretty simple, and does only the bare minimum.  Every class that wants to participate in a repository must implement IModel, this tells the repository that anything in it is guaranteed to have an int ID property, by which it can query:

 

public interface IModel{
	int ID { get; set; }
}
1
2
3

Let's say you create a class, Customer.  In order to enable it to be usable in a repository, it needs to implement IModel, so the class might look something like this:

public class Customer : IModel {

  public int ID { get; set; } //required by IModel

  public string FirstName{ get; set; }

  public string LastName{ get; set; }

}
1
2
3
4
5
6
7
8
9

Using the repository is simple,

//first create a customer repository
IRepository repo = new Repository();

//now add some customers
repo.Save(new Customer() { FirstName = "Chris", LastName = "Carter" });
repo.Save(new Customer() { FirstName = "Emmitt", LastName = "Carter" });

//make sure they are in there
Assert.AreEqual(2, repo.Count);
Assert.AreEqual("Emmitt", repo.Find(2).FirstName);

//let's remove one
repo.Delete(repo.Find(2));

//make sure it's gone
Assert.AreEqual(1, repo.Count);
Assert.IsNull(repo.Find(2));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

I bundled up the code in a project inspired by Rhino Commons called EPS.Common, the source is here: http://svn.chrisjcarter.com/public/EPS.  I have a sample ASP.NET MVC(Preview 4) solution available for download here(less than 100k).

 
Author: , 0000-00-00