Building a Simple Blog Engine with ASP. net mvc and LINQ-Part 3

Source: Internet
Author: User

Original article address: Building a Simple Blog Engine with ASP. net mvc and LINQ-Part 3

Summary

In the third part of this series, Keyvan discusses the data models in the blog engine, which obtain data from the Controller and pass it to the View. With the help of the Code, he showed us the related concepts of the data model in terms of LINQ.

Content

  • Introduction
  • Data Model
  • Database Structure
  • LINQ to SQL
  • Get Data
  • Update Controller
  • Summary

Introduction

In the first and second sections of this series, I have discussed the basics of the MVC model, the concepts of ASP. NET MVC Framework and Controller and their implementation in ASP. NET MVC Framework.

In this article, I will use ASP. NET MVC Framework to implement KBlog and introduce related concepts as an example.

After learning the basic concepts of Controller, we need to find a way to load the data in the data storage system to the data model and pass it to the View to end the Controller's work.

In KBlog, I used the SQL Express database and designed three simple tables (which will be seen later ). This article will introduce you to the data model, another major component in the database structure and MVC mode, and load data and pass the data to the View using LINQ to SQL.

Before entering the subject of the article, I need to declare that although you will see the final application of some data models, the focus of this article is the concept of data terminals and Data Models in KBlog and MVC.

Data Model

The data model is one of the three main concepts in the MVC model. Its responsibility is to declare the status. The data model obtains data from the data storage system and passes it to the Controller. State data is usually stored in the database system. There are several ways to obtain them.

ASP. net mvc Framework does not care about your storage system. All you have to do is pass data to the Controller. You can use low-level APIs of ADO. NET, such as DataReader or DataSet, or use the LINQ to SQL class. Here, we use LINQ to SQL.

Generally, the data model is a proxy class. It loads data as an object and passes it to the Controller class. For convenience, many developers choose to use the Helper class, which simplifies the work of the data model and encapsulates internal work to some extent. You will see it later.

Database Structure

The database structure of KBlog is very simple. It contains three tables: Posts, Comments, and Categories. The relationship between them is obvious.

Figure 1

The database structure is clear at a glance. As long as the multi-Blog engine has a basic understanding, it can be understood, so we will not go into details.

LINQ to SQL

In KBlog, I plan to use the LINQ to SQL mechanism to load and transmit data to the data model. Using LINQ to SQL is very simple and should be called a required knowledge of. NET developers. However, it is necessary to introduce it because it is a new technology. In the ASP. net mvc projectModelsCreate a new LINQ to SQL Classes entry in the folder, as shown in figure 2.

Figure 2

After adding this item, you can drag the database table to the designer without any other operations. In this example, this is enough.

Figure 3 shows the shape of your LINQ to SQL designer.

Get Data

As mentioned earlier in this article, developers usually prefer to use the proxy class to hide the internal data loading work, So I createKBlogDataContextAnd define some methods to load data objects.

The methods in this class use the LINQ to SQL object and the LINQ declaration to load data. The code 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 in the code, and I am not going to introduce them in detail, because it is very simple and beyond the scope of this series.

There are four methods in the Code:

  • GetCategoryPosts: returns the list of articles belonging to this category by category name.
  • GetRecentPosts: returns the last N articles displayed on the homepage.
  • GetPost: returns a single article through the primary key.
  • GetCategories: returns the list of all categories.

Although this is not necessary, I strongly recommend that you organize your applications in this way to encapsulate data operations well and make the code in the Controller easy to read.

Update Controller

Very good! After learning the data model, it is time to update the Controller class. We modify its implementation to apply the data model method and load and transmit data.

In the second article of this series, we created three Controller classes that contain three Action methods. Now we use the data model method to update them.
First, update the HomeController class and its Index method. The modified code is shown 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 can see, I use the KBlogDataContext class and its GetRecentPosts method to retrieve the article list and pass it to the RenderView method. The RenderView method obtains the status data and view name and passes the data to the view. Others will be processed in the view, which will be discussed in subsequent articles.

The second Controller is CategoriesController, which is responsible for retrieving all the article data of a certain type. The modified 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, which loads individual article data 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 question you want to ask is the RenderView method and view-related content. We will introduce view-related details in subsequent articles, so don't worry.

Summary

The third part of the ASP. net mvc Framework series introduces data model components. First, we introduce the data model and provide the database structure. Next, we quickly browsed the process of loading data using LINQ to SQL. In the data model, use LINQ to SQL to obtain data in the database. Finally, use the data model in the Controller to transmit data to the View.

More unit tests, views, and URL Routing will be introduced in subsequent articles.

In the next article, I will publish the source code of KBlog to you.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.