What is the right way to use repository pattern (with entity framework) when working with multiple set of entities?
Should I create a repository for every entity?
e.g.:
Having following entities: Articles, categories and comments.
Should i have a repository for each one?
I was using repository like this:
public class BaseArticleRepository : BaseRepository
{
private ContentModel _contentctx;
public ContentModel Contentctx
{
get
{
if ((_contentctx == null))
{
_contentctx = new ContentModel();
}
return _contentctx;
}
set { _contentctx = value; }
}
// IDisposable Support code comes here....
}
And sample repository for Articles:
public class ArticlesRepository : BaseArticleRepository
{
public Article GetArticleById(int id)
{
var article = Contentctx.Articles.Where(o => o.ArticleID == id).FirstOrDefault();
return article;
}
public List<Article> GetArticles()
{
var articles = Contentctx.Articles.ToList();
return articles;
}
public List<ArticleHeader> GetArticlesHeaders()
{
var articles = (from article in Contentctx.Articles
select new ArticleHeader
{
ArticleID = article.ArticleID,
Title = article.Title,
CategoryTitle = article.Articles_Categories.Title,
AddedBy = article.AddedBy,
AddedDate = article.AddedDate,
ViewCount = article.ViewCount
}).ToList();
return articles;
}
public List<ArticleHeader> GetArticlesHeaders(int PageIndex, int PageSize)
{
var articles = (from article in Contentctx.Articles
select new ArticleHeader
{
ArticleID = article.ArticleID,
Title = article.Title,
CategoryTitle = article.Articles_Categories.Title,
AddedBy = article.AddedBy,
AddedDate = article.AddedDate,
ViewCount = article.ViewCount
}).OrderBy(p => p.AddedDate).Skip(PageSize * PageIndex).Take(PageSize).ToList();
return articles;
}
public int GetArticleCount(string txtFilter)
{
int ret = Contentctx.Articles.Where(o => o.Title.Contains(txtFilter)).Count();
return ret;
}
public int AddArticle(Article article, int categoryId)
{
Contentctx.AddToArticles(article);
}
}
Basically every repository implements all CRUD data (including getting data with filters and sorts), though I read in some blogs that this is wrong repository pattern implementation because Repository must implement only basic,generic, function to retrieve and insert (remove modify) data.
All sorting, filtering must be done locally in memory.
But I preform to what ever i can on server side (sqlserver).
Why should I load all articles (with all fields) from database if I need only title and abstract?