10. Create a model layer using LINQ to SQL

Source: Internet
Author: User

This articleArticleWe have built a movie database for management.ProgramHere we create a Movie Database Management Program in an extremely fast and simple way, and operate the database directly at the control layer.
Next we will learn how to use the reporsitory mode. Using the repository mode requires additional effort, but it can make our program easier to test and better respond to changes.

I. What is model class?
The MVC model layer contains all the logic except the view layer and control layer.,The MVC model layer contains allBusiness LogicAndData access logic
We can use different technologies to implement data access logic. For example, we can use the Microsoft Entity Framework, nhib.pdf, subsonic, or ADO. Net class to build it.
In this article, we use LINQ to SQL to query and update databases. LINQ to SQL provides a very simple interface for me to operate SQL Server databases, but do not think ASP. net MVC framework can only be used together with LINQ to SQL, Asp. net MVC is compatible with any data access technology.

2. Create a movie data database
In this article, we create a simple Movie Database Management Program to demonstrate how to create model classes.
The first step is to create a new database. In the solution folder, right-click the app_data folder and select "add"-"new item". In the displayed dialog box, select SQL Server database and name it moviesdb. MDF. Click Add,

Figure 1
After creating a new database, double-click the moviesdb. MDF file in the app_data folder to open sqlserver explorer, as shown in

Figure 2
Now we add a table to the database to save the movie information. In sqlserver explorer, right-click the tables folder and choose "add"-"New table" to open the database design interface,

Figure 3
We need to do two things on the ID column. First, we need to mark the ID column as the primary key column. During insert and update operations on data, we need to specify the primary key column information, second, you need to mark the ID column as an auto-increment column.

3. Create a LINQ to SQL class
The MVC model layer of our program contains the LINQ to SQL class for the tblmovie database.A simple way to create a LINQ to SQL class is: Right-click the models folder, select "add"-"new item", and select "LINQ to SQL classes" in the displayed dialog box, and name it move. dbml: click "add.

Figure 4
After creating the LINQ to SQL class, the object relational designer is displayed. We drag the table from the Server Explorer window to the object relation designer, and the data table is displayed on the designer.

Figure 5
By default,When we drag a table to object relation designer, object relation designer creates a corresponding class. If we don't want to name our class with the same name as the table (tblmovie), click the class name in the designer to change it to what you want.
Remember to click the Save button to generate and save our LINQ to SQL class. Otherwise, the object relation designer will not generate the LINQ to SQL class.

4. Use LINQ to SQL in controller actions
Now that we have the LINQ to SQL class, we can use these classes to retrieve data from the database. In this section, we will learn how to use the LINQ to SQL class in the Controller action to directly access the database and display the tblmovies table information at the view layer.
First, modify the homecontroller class, which can be found in the controllers folder of the application. Put the class Code Changed to the following format:
Listing 1-controllers \ homecontroller. CS
Using system. LINQ;
Using system. Web. MVC;
Using mvcapplication1.models;
Namespace mvcapplication1.controllers
{
[Handleerror]
Public class Homecontroller: Controller
{
Public actionresult index ()
{
VaR datacontext = new moviedatacontext ();
VaR movies = from m in datacontext. Movies select m;
Return view (movies );

}
}
}

In the index () action of the code above, we use the datacontext (moviedatacontext class) of LINQ to SQL to operate the moviedb database. The moviedatacontext class is automatically generated by the object relation designer.
To query all data in a tblmovies table, use datacontext. The movie list data is assigned to the local variable movies. Finally, the Movies list is transmitted to the view layer through viewdata.
To display all movie information, we need to modify the application views/home/index view. The Code is as follows:
Listing 2-views \ home \ index. aspx
<% @ page Language = "C #" masterpagefile = "~ /Views/shared/site. master "autoeventwireup =" true "codebehind =" index. aspx. CS "inherits =" mvcapplication1.views. home. index "%>
<% @ import namespace =" mvcapplication1.models "%>


    <% foreach ( movie m in (ienumerable) viewdata. model )
    {%>
  • <% = m. title %>

  • <% }%>



The above Code contains <% @ import namespace = "mvcapplication1.models" %>, which imports the mvcapplication1.models namespace. mvcapplication1.models is the namespace where our model class is located.
The above code contains a foreach loop iteration of every item in viewdata. model. The title of each movie is displayed.
We can see that in the above Code, we forcibly convert viewdata. Model to the ienumerable type. Only in this way can we iterate the data returned by viewdata. model.
If we run the program now, we will find a blank page, because we have not added data to the database, right-click the tblmovies table in the Server Explorer window, select "show table data" in the pop-up menu and enter the data.

Figure 6
When we add records to the database table and run the program, we will find that all the movie data is displayed in the list ..

Figure 7

5. Use the repository Mode
In the previous section, we directly used the LINQ to SQL class in the Controller action. In simple applications, this approach is not a problem, but for complex programs, this method of writing data to SQL directly in the Controller will cause us a lot of trouble.
This method of writing LINQ to SQL directly in the Controller will become very difficult in the future when we change the database access technology. .For example, we can use Microsoft Entity Framework to replace Microsoft LINQ to SQL to access the database in the future. Once we do this, we need to modify the code of each controller.
In addition, writing the LINQ to SQL code directly in the controller makes it difficult for us to write unit tests for applications. Generally, when we perform unit tests, we do not need to directly interact with the database, because what we want to test is our program logic, not the database server.
To make MVC applications easier to maintain and test, we should consider using the repository mode.
We create an interface that defines the method declarations required for database operations. Then we write a class to implement the interface methods in the class and adopt a certain database access technology to operate the database. In the controller, we write code based on the interface, so that we can change the database access technology in the future without modifying the controller.
Here we have compiled an interface imovierepository, which defines a method listall ();
Listing 3-models \ imovierepository. CS
Using system. Collections. Generic;
Namespace mvcapplication1.models
{
Public interface imovierepository
{
Ilist <movie> listall ();
}
}
Then write a movierepository class to implement the imovierepository interface, and implement the listall () method in this class ().
Listing 4-models \ movierepository. CS
Using system. Collections. Generic;
Using system. LINQ;
Namespace mvcapplication1.models
{
Public class Movierepository:Imovierepository
{
Private moviedatacontext _ datacontext ;
Public Movierepository ()
{
_ Datacontext = new moviedatacontext ();
}
# Region imovierepository members
Public ilist <movie> listall ()
{
VaR movies = from m in _ datacontext. Movies select m;
Return movies. tolist ();
}
# Endregion
}
}

Finally, we use the repository mode in the Controller moviescontroller, instead of using the LINQ to SQL class to operate the database directly.
Listing 5-controllers \ moviescontroller. CS
Using system. Web. MVC;
Using mvcapplication1.models;
Namespace mvcapplication1.controllers
{
Public class Moviescontroller: Controller
{
Private imovierepository _ repository;
Public Moviescontroller (): This (New movierepository ())
{
}
Public moviescontroller (imovierepository repository)
{
_ Repository = repository;
}
Public actionresult index ()
{
Return view (_ repository. listall ());
}
}
}
In the above Code, the moviescontroller class has two constructors, The first constructor is a non-parametric constructor. When the constructor is called, create a movierepository class instance and pass the instance to the second constructor.
The second constructor has an imovierepository constructor. This constructor assigns the passed parameters to the member Variable _ repository.
The moviescontroller controller is designed to implement the dependency injection mode, that is, we often say "construct dependency injection ". For more information about dependency injection, see Martin Fowler.
Http://martinfowler.com/articles/injection.html

We also need to note that,In the moviescontroller class, we interact with the imovierepository interface instead of directly interacting with the movierepository class. This is what we often say: "We need to rely on abstraction rather than concrete ."

When we want to modify the database access code, we only need to write another class, which also implements the imovierepository interface. Assume that we have created the entityframeworkmovierepository class or subsonicmovierepository class. Because our controller is based on interface encoding, we input an instance of the above two classes when constructing the controller, then the controller and related classes should work together.

If we want to test the moviescontroller class, we can upload a fake class to the moviescontroller. This fake class also implements the imovierepository interface, but does not actually access the database. In this way, we can only test the moviescontroller class without using the real data access logic.

Summary
This article demonstrates how to use LINQ to SQL to create an MVC model class.
First, we need to create a LINQ to SQL class and then use these classes directly in the Controller action. This approach allows us to quickly and easily display data in the database in the MVC application.
Then, we made the problem a little more complicated, but the data display was more flexible and the program was more flexible. This is because the repository mode is used. This mode places all the database access logic in one model class. In the controller, we only program interfaces, which makes it much easier for us to change the data access method in the future and makes the program easier to test.

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.