AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=1604&pId=-1
Building a Simple Blog Engine with ASP.NET MVC and LINQ - Part 3
page
by Keyvan Nayyeri
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 60274/ 100

Introduction

In the first and second parts of this article series I talked about the fundamentals of the Model View Controller (MVC) pattern and the ASP.NET MVC framework as well as the controller concept in the MVC pattern and its implementation in the ASP.NET MVC framework.

Moving on in this discussion, I want to implement KBlog with the MVC framework as a simple blog engine and show the concepts related to the ASP.NET MVC framework by using it as an example.

After getting started with controllers and learning the basics about them, we need to find a way to load data from data storage in data model and pass them to views in order to finalize the work on controllers.

For KBlog I'm using a SQL Express database with three simple tables that you'll discover in a moment. In this part of the article series I introduce you to the data model as the other main component in Model View Controller (MVC) framework and the database structure then will use LINQ to SQL to load data and pass the loaded data from LINQ to views in controllers.

Before stepping in the main body of the article let me say that this part focuses on the data side and data model concepts of the KBlog and MVC even though you'll see some final uses of our data model in the article.

Data Model

Data model is one of the main three components of MVC pattern and is actually responsible to maintain the state. Data model retrieves data from data storage systems and passes the data to controllers. Often the state data is stored in database storage system and you can retrieve them in several ways.

ASP.NET MVC framework doesn't care about your storage system and all you need to do is pass your data to the controller classes somehow. This may be via lower level APIs of ADO.NET like DataReader or DataSet or via LINQ to SQL classes. Here for KBlog I'll use LINQ to SQL which will become common in the near future (if we don't consider it as something common for real world projects right now).

In general the data model is a proxy class that loads data as objects and can pass them to controller classes. For simplicity many developers prefer to use some extra helper classes that simplify the work with the data model and encapsulate the inner workings to some extent. You'll see this later in this article.

Database Structure

The structure of the KBlog database is very simple. It has three tables named Posts, Comments, and Categories that have some obvious relationships as you see in Figure 1.

Figure 1

The structure of this database is self-explanatory and anyone with a very basic understanding of blogging engines can find what's going on here so I won't waste your time with any description about the database.

LINQ to SQL

For KBlog I want to use a LINQ to SQL mechanism to load data to the data model and pass them to controller actions. Using LINQ to SQL is pretty easy and should be common knowledge for a normal .NET developer, but since it's a new technology just let me point that you can add a new LINQ to SQL Classes item to your Models folder in ASP.NET MVC project as shown in Figure 2.

Figure 2

After adding this item to your project you can drag and drop database tables to the designer and don't need to do anything else because this is all we need for this example.

Your LINQ to SQL designer should look like Figure 3 after that.

Figure 3

Fetch Data

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.

Update the Controllers

Very well! After learning about the data model, now it's time to update our implementation of controller classes to apply the data model methods and load data and pass the data to views.

If you can remember from the second part of this series, we had three controller classes with three action methods included in them. Here we updated them to use data model methods.

First controller to update is the HomeController and its Index action method. The updated code is presented in Listing 2.

Listing 2:

using System;
using System.Web;
using System.Web.Mvc;
using KBlog.Models;
using System.Collections.Generic;
 
namespace KBlog.Controllers
{
    public class HomeController : Controller
    {
        // Sample URL: /Default.aspx
        [ControllerAction]
        public void Index()
        {
            KBlogDataContext dataContext = new KBlogDataContext();
            List<Post> posts = dataContext.GetRecentPosts(10);
 
            RenderView("Index", posts);
        }
    }
}

As you see I used the KBlogDataContext class and its GetRecentPosts method to retrieve a list of posts and pass them to RenderView method. RenderView is a method that gets state data and a view name and passes the data to view. The rest will be done in views that we'll discover in future article parts.

The second controller is CategoriesController where we retrieve the data for all the posts in a specified category and the updated code is shown in Listing 3.

Listing 3:

using System;
using System.Web;
using System.Web.Mvc;
using KBlog.Models;
using System.Collections.Generic;
 
namespace KBlog.Controllers
{
    public class CategoriesController : Controller
    {
        // Sample URL: /Category/DotNet
        [ControllerAction]
        public void Category(string name)
        {
            KBlogDataContext dataContext = new KBlogDataContext();
            List<Post> posts = dataContext.GetCategoryPosts(name);
 
            RenderView("Category", posts);
        }
    }
}

The last controller is PostsController that loads data for an individual post and passes it to the appropriate view (Listing 4).

Listing 4:

using System;
using System.Web;
using System.Web.Mvc;
using KBlog.Models;
using System.Collections.Generic;
 
namespace KBlog.Controllers
{
    public class PostsController : Controller
    {
        // Sample URL: /Post/25
        [ControllerAction]
        public void Post(int id)
        {
            KBlogDataContext dataContext = new KBlogDataContext();
            Post post = dataContext.GetPost(id);
 
            RenderView("Post", post);
        }
    }
}

The only thing that you may ask about is the RenderView method and stuff related to views. Hopefully we will cover views in more details in next parts so don't worry about them!

Previous Articles in this series
Summary

This third part of my article series about ASP.NET MVC framework was all about the data model component of the pattern. First it introduced you to the data model then gave a general description about the database structure. After that, you saw a quick overview of the process of using LINQ to SQL to load data. The next topic was applying these to fetch data from the database in a data model and finally using the data model in controllers to pass data to views.

In the future parts you'll read more about unit testing, views, and URL routing.

From the next part I'll publish the source code of KBlog for everyone who wants to get his hands on the code.


Product Spotlight
Product Spotlight 

©Copyright 1998-2021 ASPAlliance.com  |  Page Processed at 2021-12-04 9:06:41 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search