I made an ASP.NET MVC application using Entity Framework for code-first migrations to the SQL Server database. I also use Unity (DI/IoC) for managing the services and repositories.
I made an overview page but I'll limit the items on that page to 10, 50 or 100 (variable named pagecount) items as selected by the user. The rest of the items are on other pages (variable named page). The result is something similar to what Code review has:
Each Blog has a Category. I'll also that the user can see one, more, or all categories (variable named categories). This contains a list of integers with the categories that the user will see.
using System.Data.Entity;
public class BlogRepo : GenericRepo<Blog>
{
public List<Blog> GetByPage(int page, List<int> categories, int pagecount)
{
return (from b1 in ((from b2 in ((from b3 in dbSet.Include(b3 => b3.Category).Include(b3 => b3.User)
orderby b3.CreationDateStamp ascending
where categories.Contains(b3.CategoryId)
select b3).Take<Blog>(page * pagecount)).Include(b2 => b2.Category).Include(b3 => b3.User) // step one
orderby b2.CreationDateStamp descending
select b2).Take<Blog>(pagecount)).Include(b1 => b1.Category).Include(b3 => b3.User) // step two
orderby b1.CreationDateStamp ascending
select b1).ToList<Blog>(); // step tree
}
}
Here is my way of working:
I take the first items calculated by the formula
page * pagecountsorted in ascending order byCreationDateStampwherecategories.Contains(b3.CategoryId)is true.Form that items I sort it in descending order on the same property, and take the value of
pagecount.Finally, sort it again (ascending), and call
ToList<Blog>()to materialize the results.
Note one: I'll always include the properties Category (type of Category) and User (type of ApplicationUser).
Note two: the variable dbSet comes from a generic repository and is declared as follows:
public class GenericRepo<TEntity> : IGenericRepo<TEntity> where TEntity : class
{
internal DbSet<TEntity> dbSet;
// other basic linq statements for get basic stuff like GetAll, Delete, Insert, SaveChanges and Update
}
The code works, but I wondering if I can improve its performance and readability. In other words, can I combine some steps and can I reduce the code to make it shorter or simpler?
