LINQ Repository

December 11, 2007

Today I did some very fun refactoring at work. I am using a LINQ Repository interface with generics to get some free functionality.
Currently the project I’m working on at work is an asp.net 3.5 project and has 3 projects that make up the solution.
The first is a DB Pro project that has all the sql scripts inside it. The “middle” project is named core and it holds all the business and data layer logic, and lastly the asp.net project. In the core project I would have all my entities that are partial classes and call upon LINQ functionality for my CRUD operaions. And Lastly the asp.net project. From the asp.net project I would call upon the core project’s partial entity classes for my operations. For example.
I want to bind a product to my listview, so the code might look something like this.

ListView1.DataSource = Product.Get(productID);

and within Product.Get(int ProductID) you may have something along the lines of:

return Product.SingleOrDefault(x => x.ID = ProductID);

Pretty standard stuff right. Now with the new “LINQ Repository” I would call


and there wouldn’t be any code within the Product class other than

class Product : IRepository

and I would get all my CRUD operations for free!

Here is the code for an example of IRepository (Note, none of this code is compiled and tested, I am doing this in the blogger’s WYSIWYG)

public interface IRepository
where T : IIdentifiable
int Count();
int Count(Expression<func> expression);

void Add(T entity);
void Remove(T entity);
void Save(T entity);

T FindOne(int id);
T FindOne(Expression<func> expression);

bool TryFindOne(Expression<func> expression, out T entity);

IList FindAll();
IList FindAll(Expression<func> expression);

IQueryable Find();
IQueryable Find(int id);
IQueryable Find(Expression<func> expression);


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: