ASP. net mvc model (using Entity Framework to create model classes)-part.1

Source: Internet
Author: User
Tags actionlink

From Zhang Ziyang http://www.cnblogs.com/JimmyZhang/archive/2009/05/18/1459326.html

The purpose of this tutorial is to explain how to create an ASP. net mvc application.ProgramHow to use Microsoft Entity Framework to create a data entity class. This tutorial assumes that you have no knowledge of Microsoft Entity Framework in advance. After reading this tutorial, you will understand how to use Entity Framework to select, insert, update, and delete database records.

Microsoft Entity Framework is an object relationship ing (O/RM) tool that allows you to automatically generate a data access layer from the database. The Entity Framework prevents you from writing lengthy data entity classes.

To demonstrate how to use 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, Visual Web Developer 2008, and service pack1. To use Entity Framework, you need to use service pack1. You can download Visual Studio 2008 service pack1 or visual web developer with service pack1 from the address below:

Http://www.asp.net/downloads/

Note:There is no necessary link between ASP. net mvc and Microsoft Entity Framework. In addition to using Entity Framework, ASP. net mvc also provides several optional methods. For example, you can use other O/RM tools, such as Microsoft LINQ to SQL, nhib.pdf, or subsonic, to create your MVC model class.

1. Create a movie instance Database

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

Column name Data Type Allow null Primary Key?
ID Int False True
Title Nvarchar (100) False False
Director Nvarchar (100) False False

You can add the table to the ASP. net mvc project using the following steps:

    1. Right-click the app_data folder in solution browser, and select the menu item "add" and "new item ".
    2. In the "Add new item" dialog box, select "SQL Server database", name the database moviesdb. MDF, and click "add.
    3. Double-click the moviesdb. MDF file to open the "server resource manager/Database Resource Manager" window.
    4. Expand the moviesdb. MDF database connection, right-click the "table" folder, and choose "Add new table" from the menu )".
    5. In the Table Designer, add the ID, title, and ctor columns.
    6. Click Save to save the new table as movies.

After creating a movies database table, you should add some sample data to the table. Right-click the movies table and choose show table data from the menu )". You can input fictitious movie data to the displayed grid.

2. Create an ADO. Net Object Data Model

To use the Entity Framework, you need to create an Entity Data Model ). You can use the Visual Studio Object Data Model Wizard (Entity Data Model Wizard) to automatically generate an object data model from the database.

Follow these steps:

    1. Right-click the models folder in the solution browser window, and select the menu items, add and new items )".
    2. In the Add new item dialog box, select data category (1 ).
    3. Select the ADO. NET Entity Data model template, name the Object Data Model moviesdbmodel. edmx, and click "add. Click "add" to run the Data Model Wizard.
    4. In the "select model content (Choose Model contents)" step, select the "generate from database" option, and click the "Next" button (2 ).
    5. In the "Select data connection (choose your data conncetion)" step, select moviesdb. MDF database connection, enter the connection name of the object, moviesdbentities, and click "Next" (3 ).
    6. In the "select your database object (choose your database object)" step, select the Movie Database Table and click "finish" (4 ).

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

Figure 1-create a new object data model

Figure 2-procedure for selecting model content

Figure 3-Select data connection

Figure 4-select your database object

3. Modify the ADO. Net Object Data Model

After creating an object data model, you can use the object designer (5) to modify the model. Double-click the moviesdbmodel. edmx file in the models folder in solution browser. You can open the Entity Designer at any time.

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 creates a new data category class called movies. In other words, the name of this class in Wizard is exactly the same as that in the database. Because we will use this class to represent a specific movie instance, we should rename this class from movies to movie.

To rename an object class, double-click the Class Name of the object designer and enter a new name (6 ). Alternatively, you can select an object in the Entity Designer and modify the object class name in the Properties window.

Figure 6-change an object name

Remember to click "save" after making the modification to save your "Entity Data Model ". Behind the scenes, the Entity Designer generates a series of C # classes. Open the moviesdbmodel. Designer. CS file in the Solution Explorer window. You can view these classes.

Note:Do not modify it in the designer. CS FileCodeBecause your changes will be overwritten the next time you use the Entity Designer. If you want to extend the object class function defined in designer. CS, you can create a category in a separate file.

4. Use Entity Framework to select database records

Let's start building our movie database application by creating a page that displays the movie record list. The Home controller in code 1 releases an action named index. By using Entity Framework and index (), all movie records from the movie database table are returned.

Code List 1-controllershomecontroller. CS

UsingSystem. LINQ;

UsingSystem. Web. MVC;

UsingMovieentityapp. models;
NamespaceMovieentityapp. controllers {
[Handleerror]

Public Class Homecontroller:Controller{

Moviesdbentities_ DB;
PublicHomecontroller (){

_ DB =New Moviesdbentities();

}
PublicActionresult index (){

Viewdata. Model = _ dB. movieset. tolist ();

ReturnView ();

}
}

}

Note that the Controller in code 1 contains a constructor. This constructor initializes a class-level field called _ dB. The _ DB field represents the database entity generated by Microsoft Entity Framework. The _ DB field is an instance of the moviesdbentities class, which is generated by the "Entity Designer.

Note: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 obtain records in the movies database table. Expression _ dB. movieset indicates all records from the movies database table. The tolist () method is used to convert a movies record set to a generic set of movie objects (list <movie> ).

Movie records are obtained with the help of LINQ to entities. The index () Action in code 1 uses the method syntax to obtain the record set of the database. If you want to, you can also use the query syntax ). The following two statements complete the same process:

Viewdata. Model = _ dB. movieset. tolist (); viewdata. Model = (from mIn_ DB. movieset select M). tolist ();

Use the method or query syntax, which is one of the most sensible LINQ syntaxes. The two methods have no performance difference-the only difference is style.

The view in code list 2 is used to display the movie record.

Code List 2-viewshomeindex. 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"> <HTML xmlns = "http://www.w3.org/1999/xhtml">

<Title> index </title>

</Head> <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}) %>

<HR/>

<% }%>
<% = Html. actionlink ("add movie", "add") %>

</Div> </body>

The view in code list 2 contains a foreach loop that traverses every movie record and displays the title and ctor attribute values of the movie record. Note that the edit and delete links are displayed next to each record. In addition, the Add movie link is displayed at the bottom of the view (7 ).

Figure 7-index View

The index view is a typed view ). The index view contains a <% @ Page %> indicator, which contains an inherits attribute, it forcibly converts the model attribute to a list of strong-type generic lists (list <movie>) of a movie object ).

5. Use Entity Framework to insert database records

You can use Entity Framework to easily Insert new records into database tables. Code listing 3 contains two new actions added to the home controller class. You can use these actions to insert new records into the movie database table.

Code List 3-controllershomecontroller. CS (add method)

PublicActionresult add (){

ReturnView ();

}
[Acceptverbs (httpverbs. Post)]

PublicActionresult add (formcollection form ){
VaRMovietoadd =New Movie();
// Deserialize (include White List !)

Tryupdatemodel (movietoadd,New String[] {"Title", "director"}, Form. tovalueprovider ());
// Validate

If(String. Isnullorempty (movietoadd. Title ))

Modelstate. addmodelerror ("Title", "titleIsRequired! ");

If(String. Isnullorempty (movietoadd. Director ))

Modelstate. addmodelerror ("Director", "DirectorIsRequired! ");
// 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 (8) used to add new movie database records ). When you submit a form, the second add () action is called.

Note that the second add () action is modified using the acceptverbs feature. This action is called only when the http post operation is executed. In other words, this action is called 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 ASP. net mvc tryupdatemodel () method. The tryupdatemodel () method accepts the formcollection fields passed to the add () method, and assigns the values of these HTML form fields to the movie class.

Note:When you use entity frmaework, when you use tryupdatemodel or updatemodel to update attributes of an object class, you must provide a "whitelist" of attributes ".

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

If no verification error occurs, a new movie record will be added to the movies database table with the help of 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 the Code adds a new movie object 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. Update database records using Entity Framework

You can use Entity Framework to edit a database record in almost the same way as inserting a new database record. Code list 4 contains two new controller actions, called edit (). The first edit () action returns an HTML form for editing a movie record. The second edit () action attempts to update the database.

Code list 4-controllershomecontroller. 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,New String[] {"Title", "director"}, Form. tovalueprovider ());
// Validate

If(String. Isnullorempty (movietoupdate. Title ))

Modelstate. addmodelerror ("Title", "titleIsRequired! ");

If(String. Isnullorempty (movietoupdate. Director ))

Modelstate. addmodelerror ("Director", "DirectorIsRequired! ");
// If valid, save movie to database

If(Modelstate. isvalid)

{

_ DB. savechanges ();

ReturnRedirecttoaction ("Index");

}
// Otherwise, reshow form

ReturnView (movietoupdate );

}

When the second edit () action starts, obtain a movie record from the database that matches the movie ID to be edited. The following LINQ to entities statement obtains the first database record matching this specific ID.

VaRMovietoupdate = _ dB. movieset. First (M => M. ID = ID );

Next, the tryupdatemodel () method is used to assign the value of the HTML form field to the attribute of the movie object. Note that a whitelist is provided to specify which fields to update.

Next, perform some simple verification to verify that the title and ctor attributes of movie have values. If a value is missing from any attribute, a verification error message is added to modelstate, and modelstate. isvalid returns false.

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

When editing a database record, you must pass the ID of the record to be updated to the Controller action that executes the database update. Otherwise, the Controller action cannot know which record to update the underlying database. The Edit view in code list 5 contains a hidden form field that represents the ID of the database record to be edited.

Code List 5-viewshomeedit. 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"> <HTML xmlns = "http://www.w3.org/1999/xhtml">

<Title> edit </title>

<Style type = "text/CSS">

. Input-Validation-Error

{

Background-color: yellow;

}

</Style>

</Head>

<Body>

<Div>
<H1> edit movie <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>

</Html>

7. Use Entity Framework to delete database records

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

Code List 6-controllershomecontroller. CS (delete operation)

PublicActionresult Delete (IntID ){

// Get movie to delete

VaRMovietodelete = _ dB. movieset. First (M => M. ID = ID );
// Delete

_ DB. deleteobject (movietodelete );

_ DB. savechanges ();
// Show index View

ReturnRedirecttoaction ("Index");

}

The Delete () action first obtains a movie object, which matches the ID passed to the action. Next, movie is deleted from the database by calling the deleteobject () method and the subsequent savechanges () method. Eventually, 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 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 discuss how to use the Entity Data Model Wizard to generate an object data model from Visual Studio. Next, you learned how to obtain a series of database records from a database table by using LINQ to entities. Finally, we use Entity Framework to insert, update, and delete database records.

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.