Sunday, November 27, 2011

Learning MVC: A Repository Pattern.

A repository is just a place where data querying is encapsulated. There are several main reasons for a repository:

  • Avoid repetition. If I need to write a query, I will first check the repository - maybe it was already implemented
  • Encapsulation. Keep all data related code in the same place. Makes refactoring easier and separates logic from data
  • Unit testing. Tests can be written against the repository and, if necessary, in such way that the real database is not required

For the purpose of my sample application, which I explain later, I will now add a repository for the "In Basket". It's extremely simple: each user can have multiple items in the basket. A user can view, edit and delete any of his items. So I need a small number of methods:

public class InBasketRepository
{
private modelGTDContainer db = new modelGTDContainer();

//return all in basket items for a certain user
public IQueryable FindUserInBasketItems(int userID)
{
return db.InBaskets.Where(item => item.UserID == userID);
}

public InBasket GetInBasketItem(int id)
{
return db.InBaskets.Single(item => item.InBasketID == id);
}

public void AddInBasketItem(InBasket item)
{
db.InBaskets.AddObject(item);
}

public void DeleteInBasketItem(InBasket item)
{
db.InBaskets.DeleteObject(item);
}

//persistence
public void Save()
{
db.SaveChanges();
}
}

It seems logical for the repository to exist in the Models folder.

And that's it for now - the next step is to create view(s) which will use the repository.

by . Also posted on my website

No comments: