In this blog post we will create a simple data access layer that allows our UI to interact with our data. This will be hand coded for the most part, luckily it doesn’t take much code to get it all together. :)
First Things First
The first thing i am going to do is create a generic repository interface that my other repositories will implement.
1: public interface IRepository<T> where T : IPerstistable
3: void Add(T item);
5: IQueryable<T> GetAll();
7: T GetItemByID(int id);
9: void Delete(T item);
11: int Count();
13: void Save();
There is nothing too crazy here, I have created my generic interface and constrained my Type parameter saying that it must implement the IPersistable interface. This interface allows me to easily create a mock for testing!
Putting it to Work
Now I need to create a class that implements my interface, and ties in open access.
For this this to work well in a web environment, we want to make sure that we use one Object Scope through out the life of a request. This being the case, I want to go ahead and inject my open access scope into my repositories, so that i can control when my object scope is created and when it is disposed. I know we can easily do this using DI, however I want to show how it can be handled without it.
So we will first create a protected field of IObjectScope, which will allow all class that extend this repository class to access it, and then we will create a constructor that requires a scope object.
1: protected IObjectScope scope;
3: public Repository(IObjectScope objectScope)
5: scope = objectScope;
Also, when i implement my interface, i am going to mark the methods virtual, to allow derived classes to override the methods if needed.
1: public virtual void Add(T item)
6: public virtual IQueryable<T> GetAll()
8: var query = from items in scope.Extent<T>()
9: select items;
11: return query;
14: public virtual T GetItemByID(int id)
16: var query = from items in scope.Extent<T>()
17: where items.ID == id
18: select items;
20: return query.FirstOrDefault<T>();
23: public virtual void Delete(T item)
29: public virtual int Count()
31: return scope.Extent<T>().Count();
34: public virtual void Save()
Now we can create specific implentations of our repository class. I will create one for AssetGroup, Asset, and Alerts because these are my “root objects”.
Once these things are finished, we are ready to start working on our UI, so in the next blog we will take a look at large data concerns when working on with a web UI. So check back soon! Also, I have created a video that goes a little more in-depth about handling Object scope when using MVC, It should be uploaded shortly to Telerik TV.