ASP. NET MVC Entity Framework

Source: Internet
Author: User
Tags http post actionlink

ASP. NET MVC model (Create model class using Entity Framework)-Part.1

The purpose of this tutorial is to explain how to use the Microsoft Entity Framework to create a data access class when you create an ASP. NET MVC application. This tutorial assumes that you have no prior knowledge of the Microsoft Entity Framework. After reading this tutorial, you will understand how to use the Entity Framework to select, INSERT, UPDATE, and delete database records.

The Microsoft Entity Framework is an object-relational mapping (O/RM) tool that allows you to automate the generation of data access layers from a database. The Entity framework allows you to avoid manually writing lengthy data access classes.

To demonstrate how to use the Microsoft Entity Framework in ASP. NET MVC, we will create a simple sample application. We will create a movie database application that allows you to display and edit movie Database records.

This tutorial assumes that you have visual Studio 2008 or Visual Web Developer 2008 and service Pack1. In order to use the entity Framework, you need to use service Pack1. You can download Visual Studio service Pack1 or visual Web Developer with service Pack1 from the address below:

http://www.asp.net/downloads/

Note: There is no necessary connection between ASP. NET MVC and the Microsoft Entity Framework. In addition to using the entity Framework in ASP. NET MVC, you have several options. For example, you can use other O/RM tools, such as Microsoft LINQ to sql,nhibernate or subsonic, to create your MVC model class.

1. Create the Movie sample database

The Movie Database application uses a database table called movies, which contains the following columns:

Column Name Data type Allow null Whether the primary key
Id Int False True
Title nvarchar (100) False False
Director nvarchar (100) False False

You can use the following steps to add this table to an ASP. NET MVC Project:

    1. Right-click on the App_Data folder in the Solution browser and select menu item "Add", "New Item".
    2. In the Add New Item dialog box, select SQL Server database, name the databases Moviesdb.mdf, and click the Add button. "
    3. Double-click the Moviesdb.mdf file to open the Server Explorer/Database Explorer window.
    4. Expand the Moviesdb.mdf database connection, right-click the Tables folder, and select the menu option "Add New Table".
    5. In Table Designer, add the ID, title, and director columns.
    6. Click the Save button (it has a floppy disk icon) to save the new table as movies.

After you have created the Movies database table, you should add some sample data to the table. Right-click on the Movies table and select menu item "Show Table Data". You can enter some fictional movie data into the displayed grid.

2. Create an ADO Entity Data model

In order to use the entity Framework, you need to create an Entity Data model. You can use the Visual Studio Entity Data Model Wizard to automatically generate an Entity Data model from a database.

Follow the steps below:

    1. Right-click on the Models folder in the Solution Explorer window and select menu item, add, new item (newly item).
    2. In the Add New Item dialog box, select the Data category (1).
    3. Select the ADO. Entity Data Model template, name the MOVIESDBMODEL.EDMX, and click the Add button. Clicking the "Add" button will run the Data Model Wizard.
    4. In the Select model content (Choose model Contents) step, select the "Generate from Database (Generate from a)" option, and click the "Next" button (2).
    5. In the Select data connection (Choose Your) step, select the Moviesdb.mdf database connection, enter the connection settings name for the entity Moviesdbentities, and click the Next button (3).
    6. In the Select your database objects (Choose Your database object) step, select the Movie Databases table and click the "Finish" button (4).

After you have completed these steps, the ADO will open. NET Entity Data Model Designer (Entity Designer).

Figure 1-Create a new Entity Data model

Figure 2-Selecting a model content step

Figure 3-Select data connection

Figure 4-Select your database object

3. Modify the ADO Entity Data Model

After you have created the Entity Data model, you can use the Entity Designer (5) to modify the model. You can open the Entity designer at any time by double-clicking the moviesdbmodel.edmx file in the Models folder in the solution browser.

Figure 5-ado.net Entity Data Model Designer

For example, you can use the Entity Designer to change the class name generated by the Entity Model Data Wizard. The wizard created a new data access class called movies. In other words, the wizard's naming of this class is exactly the same as the table name in the database. Since we will use this class to represent a particular instance of the movie, we should rename the class from movies to movie.

If you want to rename an entity class, you can double-click on the class name of the Entity designer and enter a new name (6). Alternatively, you can select an entity in the Entity designer and then modify the name of the entity class in the Properties window.

Figure 6-Changing an entity name

Remember to save your "Entity Data Model" by clicking the "Save" button after making your changes. Behind the scenes, the Entity Designer generates a series of C # classes. You can view these classes by opening the MoviesDBModel.Designer.cs file from the Solution Explorer window.

Note: do not modify the code in the Designer.cs file because your changes will be overwritten the next time you use the Entity Designer. If you want to extend the functionality of the entity classes defined in Designer.cs, you can create a partial class in a separate file.

4. Use the Entity Framework to select Database records

Let's start building our movie Database application by creating a page that shows a list of movie records. The home controller in code 1 publishes an action called Index (). All movie records from the movie Database table are returned by using the entity Framework,index () action.

Code Listing 1-controllers\homecontroller.cs

usingSystem.Linq;
usingSYSTEM.WEB.MVC;
usingMovieentityapp.models;

namespacemovieentityapp.controllers {

[HandleError]
PublicclassHomeController:Controller{
moviesdbentities_db;

PublicHomeController () {
_db =Newmoviesdbentities();
}

PublicActionResult Index () {
Viewdata.model = _db. Movieset.tolist ();
returnView ();
}

}
}

Notice that the controller in code 1 contains a constructor. This constructor initializes a class-level field called _db. The _db field represents a database entity that is generated by the Microsoft Entity Framework. The _db field is an instance of the Moviesdbentities class that is generated by the Entity designer.

Note: in order to use the Moviesdbentites class in the home controller, you must introduce the Movieentityapp.models namespace.

The _db field is used in the index () action to get the records in the Movies database table. An expression _db. MovieSet represents all the records from the Movies database table. The ToList () method is used to convert the movies recordset into a generic collection (list<movie>) of a Movie object.

The movie record is obtained with the help of LINQ to Entities. The index () action in Code 1 uses the LINQ method Syntax (methods syntax) to get the recordset for the database. You can also use the LINQ query Syntax (query syntax) if you wish. The following two lines of statements accomplish the same thing:

Viewdata.model = _db. Movieset.tolist ();
Viewdata.model = (from M in _db. MovieSet select m). ToList ();

Use any of the LINQ grammars you most feel-method syntax or query syntax. There is no difference in performance between the two methods-the only difference is style.

The view in Code Listing 2 is used to display the movie record.

Code Listing 2-views\home\index.aspx

<%@ page language= "C #"
inherits= "System.web.mvc.viewpage<list<movieentityapp.models.movie>>"%>
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<title>Index</title>
<body>
<div>

<% foreach (var m in Viewdata.model)
{%>

Title: <%= m.title%>
<br/>
Director: <%= m.director%>
<br/>
<%= html.actionlink ("edit", "edit", new {id = m.id})%>
<%= html.actionlink ("delete", "delete", new {id = m.id})%>

<%}%>

<%= Html.ActionLink ("Add Movie", "add")%>
</div>
</body>

The view in Listing 2 contains a Foreach loop that iterates through each of the movie records and displays the value of the title and director properties of the movie record. Notice that the edit and delete links appear next to each record. In addition, the ADD movie link appears at the bottom of the view (7).

Figure 7-index View

The index view is a typed view (typed views). The index view contains a <%@ Page%> indicator that contains a inherits property that casts the model property to a strongly typed generic list collection (list<movie>) for a Movie object.

5. Inserting database records using the Entity Framework

You can easily insert a new record into a database table using the Entity Framework. Code Listing 3 contains two new actions added to the home controller class that you can use to insert a record into the Movie database table.

Code Listing 3-controllers\homecontroller.cs (Add method)

PublicActionResult Add () {
returnView ();
}

[Acceptverbs (Httpverbs.post)]
PublicActionResult Add (formcollection form) {

varMovietoadd =NewMovie();

//Deserialize (Include white list!)
TryUpdateModel (Movietoadd,Newstring[] {" Title", "Director"}, form. Tovalueprovider ());

//Validate
if(String. IsNullOrEmpty (Movietoadd.title))
Modelstate.addmodelerror (" title", "title is required!");
if(String. IsNullOrEmpty (Movietoadd.director))
Modelstate.addmodelerror ("director", "director is required!");

//If valid, save movie to Database
if(Modelstate.isvalid)
{
_db. Addtomovieset (Movietoadd);
_db. SaveChanges ();
returnRedirecttoaction ("Index");
}

//Otherwise, reshow form
returnView (Movietoadd);
}

The first add () action simply returns a view. This view contains a form for adding new movie Database records (8). When you submit a form, a second add () action is called.

Notice that the second add () action is decorated with the Acceptverbs attribute. This action is only invoked when an HTTP POST operation is performed. In other words, this action is invoked only when an HTML form is submitted.

The second Add () action creates a new instance of the entity Framework movie class with the help of the ASP. NET MVC TryUpdateModel () method. The TryUpdateModel () method accepts fields that are passed to the formcollection of the Add () method, and assigns the values of these HTML form fields to the movie class.

Note: When using entity frmaework, when updating an attribute of an entity class with the TryUpdateModel or Updatemodel method, you must provide a "whitelist" of properties.

Next, the ADD () action performs some simple form validation. This action verifies that both the title and Director properties have values. If a validation error occurs, a validation error message is added to the modelstate.

If there is no validation error, a new movie record will be added to the Movies database table with the help of the Entity Framework. The new record is added to the database using the following two lines of code:

_db. Addtomovieset (Movietoadd);
_db. SaveChanges ();

The first line of code adds a new movie entity to the movies set tracked by the Entity Framework. The second line of the code saves all changes to movies to the underlying database.

Figure 8-add View

6. Updating database records using the Entity Framework

You can edit a database record using the Entity Framework almost the same way as we just inserted a new database record. The Code Listing 4 contains two new controller actions called edit (). The first edit () action returns an HTML form for editing a single movie record. The second edit () action attempts to update a database.

Code Listing 4-controllers\homecontroller.cs (Edit method)

PublicActionResult Edit (intId
{
//Get movie to update
varMovietoupdate = _db. Movieset.first (m = m.id = = Id);

Viewdata.model = movietoupdate;
returnView ();
}

[Acceptverbs (Httpverbs.post)]
PublicActionResult Edit (formcollection form)
{
//Get movie to update
varid = int32.parse (form["id"]);
varMovietoupdate = _db. Movieset.first (m = m.id = = Id);

//Deserialize (Include white list!)
TryUpdateModel (Movietoupdate,Newstring[] {" Title", "Director"}, form. Tovalueprovider ());

//Validate
if(String. IsNullOrEmpty (Movietoupdate.title))
Modelstate.addmodelerror (" title", "title is required!");
if(String. IsNullOrEmpty (Movietoupdate.director))
Modelstate.addmodelerror ("director", "director is required!");

//If valid, save movie to Database
if(Modelstate.isvalid)
{
_db. SaveChanges ();
returnRedirecttoaction ("Index");
}

//Otherwise, reshow form
returnView (movietoupdate);
}

The second edit () action starts with a movie record that matches the ID of the movie you want to edit from the database. The following LINQ to Entities statement gets the first database record that matches this particular ID.

var movietoupdate = _db. Movieset.first (m = m.id = = Id);

Next, the TryUpdateModel () method assigns the value of the HTML form field to the properties of the movie entity. Notice that a whitelist is provided to specify which fields are updated.

Next, a few simple checks are performed to verify that both the title and director properties of the movie have values. If any one of the properties is missing a value, a checksum error message is added to Modelstate, and Modelstate.isvalid will return a value of false.

Finally, if there is no validation error, the underlying Movies database table will be updated by calling the SaveChanges () method.

When you edit a database record, you need to pass the ID of the record you want to update to the controller action that performs the database update. Otherwise, the controller action will not know which record of the underlying database is being updated. The edit view in code Listing 5 contains a hidden form field that represents the ID of the database record that will be edited.

Code Listing 5-views\home\edit.aspx

<%@ page language= "C #"
inherits= "System.web.mvc.viewpage<movieentityapp.models.movie>"%>
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<title>Edit</title>
<style type= "Text/css" >

. input-validation-error
{
Background-color:yellow;
}

</style>
<body>
<div>


<form method= "POST" action= "/home/edit" >

<!--Include Hidden Id--
<%= Html.hidden ("id")%>

Title:
<br/>
<%= Html.textbox ("title")%>

<br/><br/>
Director:
<br/>
<%= Html.textbox ("director")%>

<br/><br/>
<input type= "Submit" value= "Edit Movie"/>
</form>

</div>
</body>
7. Delete database records using the Entity Framework

The last database operation we need to resolve in this tutorial is to delete the database records. You can use the Controller action in Listing 6 to delete a specific database record.

Code Listing 6-\controllers\homecontroller.cs (delete operation)

Public ActionResult Delete (int id) {
//Get movie to delete
var movietodelete = _db. Movieset.first (m = m.id = = Id);

//Delete
_db. DeleteObject (Movietodelete);
_db. SaveChanges ();

//Show Index View
return Redirecttoaction ("Index");
}

The Delete () action first obtains a movie entity that matches the ID passed to the action. Next, the movie is removed from the database by calling the DeleteObject () method and the subsequent SaveChanges () method. Finally, the user is redirected to the index view.

8. Summary

The purpose of this tutorial is to demonstrate how to use ASP. NET MVC and the Microsoft Entity framework to create a database-driven Web application. You learned how to create an application that allows you to select, INSERT, UPDATE, and delete database records.

First, we discussed how to build an Entity Data model from Visual Studio using the Entity Data Model Wizard. Next, you learned how to use LINQ to Entities to get a series of database records from a database table. Finally, we used the Entity Framework to insert, UPDATE, and delete database records.

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.