I have recently started teaching myself C# and Asp.net. I am trying to build a simple blog application. I am confused about repository pattern usage. I have seen few tutorials and the implementation varies.
For my blog application, I have two database tables (models) – blogs and comments. Currently, I have a IDbContext which looks like this:
public interface IDBContext
{
IQueryable<Blog> FindAllBlogs();
IQueryable<Blog> FindBlogsInMonth(int month);
Blog GetBlog(int id);
void Add(Blog blog);
void Update(Blog blog);
void Delete(Blog blog);
void Add(Comment comment);
//void Remove(Comment comment);
}
and I have repository which looks like this:
public class BlogRepository : IDBContext
{
private BlogDb db = new BlogDb();
public IQueryable<Blog> FindAllBlogs()
{
return db.Blogs.OrderByDescending(b => b.PublishDate);
}
public Blog GetBlog(int id)
{
return db.Blogs.Single(b => b.BlogID == id);
}
...
}
The other implementation of repository pattern is something like this:
public interface IDbContext
{
IQueryable<Blog> Blogs { get; }
IQueryable<Comments> Comments { get; }
int SaveChanges();
T Attach<T>(T entity) where T : class;
T Add<T>(T entity) where T : class;
T Delete<T>(T entity) where T : class;
}
which calls a repository and there is separate class for queries.
What is the best method to do it?
The easiest method is to use Entity Framework directly, particularly the new DbContext functionality that showed up in Entity Framework 4.1 and later.
The context will contain DbSet properties – each is an implementation of the repository pattern that accomplishes all of the goals you described above. IDbSet can be used if unit testing support is required.
I’ve seen a lot of demos for the ASP.NET MVC repository patterns online that end up wrapping Entity Framework with a custom repository. It’s a waste of time – it’s code that wraps other code and doesn’t serve any direct purpose aside from adding needless complexity.