As I stated in the previous sections of this article,
usually developers prefer to use a proxy class to hide the inner data workings
that lead to loading data so I create a class and name it KBlogDataContext
to define a few methods that will load the data objects for me and I can apply
them in my controller action methods easily.
Methods included in this class use my LINQ to SQL objects
and LINQ statements to load data. The code for this class is shown in Listing 1.
Listing 1
using System;
using System.Data;
using System.Linq;
using System.Collections.Generic;
namespace KBlog.Models
{
public class KBlogDataContext
{
public List<Post> GetCategoryPosts(string categoryName)
{
KBlogDBDataContext context = new KBlogDBDataContext();
return context.Posts.Where(
p => p.Category.Title == categoryName).ToList();
}
public List<Post> GetRecentPosts(int count)
{
KBlogDBDataContext context = new KBlogDBDataContext();
return context.Posts.Take(
count).OrderByDescending(p => p.PublishedDate).ToList();
}
public Post GetPost(int id)
{
KBlogDBDataContext context = new KBlogDBDataContext();
return context.Posts.Where(p => p.ID == id).Single();
}
public List<Category> GetCategories()
{
KBlogDBDataContext context = new KBlogDBDataContext();
return context.Categories.ToList();
}
}
}
Note that there are some simple LINQ expressions that I used
for this example, but I don't step in their details because they're easy to
read and understand and move us beyond the scope of this article series.
There are four methods defined here:
·
GetCategoryPosts: Returns a list of
posts for a specified category based on the category name.
·
GetRecentPosts: Returns recent N posts
of the blog to be shown in the homepage.
·
GetPost: Returns a single post based on
its identifier.
·
GetCategories: Returns a list of all
categories.
Even though I could get rid of this class I strongly
recommend you follow the same approach in your applications to have good encapsulation
for your data operations and have simpler and more readable code in
controllers.