ASP. NET mvc4 entry (7) Add a new field to the movie object and table

Source: Internet
Author: User

Link: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-new-field-to-the-movie-model-and-table

In this section, we will use the code first Migration Mode of the Entity Framework to bring some changes to the Model class, and these changes will also be reflected in the database.

By default, when we use the code first mode of Entity Framework to automatically create a database (just as beforeArticleCode first will want to add a table to the database to help us track whether the schema of the database is synchronized with the model class based on the database. If they are not synchronized, Entity Framework will throw an error. This will make it easy to discover problems during development, rather than bringing them into the runtime for discovery.

Set code first migration to Change Model

If you are using Visual Studio 2012, double-click movies. MDF from Solution Explorer to open the database tool. Visual Studio express displays Database Explorer and Visual Studio 2012 displays server explorer. If Visual Studio 2010 is used, SQL Server Object explorer is used.

In database tools (Database Explorer, Server Explorer, or SQL Server Object Explorer ), right-click movie and choose delete to delete the database (moviedbcontext is displayed if Visual Studio 2012 is used ).

Switch to solution Resource Manager. Right-click the database file and select Delete to remove the database file.

Regenerate the followingProgramMake sure there are no compilation errors.

Select "library Package Manager"-> "Package Manager Console" from the Tools menu"

Enter "enable-migrations-contexttypename mvcmovie. Models. moviedbcontxt" at the PM> prompt in the "Package Manager Console" window (note that there is a space after enable-migrations ).

The enable-migrations command creates a new folder named migrations and creates a configuration. CS file under the folder.

Open the configuration. CS file and use the followingCodeReplace the seed method in the file.

 Protected   Override   Void  Seed (mvcmovie. Models. moviedbcontext context) {context. Movies. addorupdate (I => I. title, New  Movie {Title = "  When Harry Met Sally  "  , Releasedate = Datetime. parse ( "  1989-1-11  "  ), Genre = "  Romantic Comedy  "  , Price =7.99 m  },  New  Movie {Title = "  Ghostbusters  "  , Releasedate = Datetime. parse ( "  1984-3-13  "  ), Genre = "  Comedy  " , Price = 8.99 m  },  New  Movie {Title = "  Ghostbusters 2  "  , Releasedate = Datetime. parse ( "  1986-2-23  "  ), Genre = " Comedy  "  , Price = 9.99 m  },  New  Movie {Title = "  Rio Bravo  "  , Releasedate = Datetime. parse ( "  1959-4-15  "  ), Genre ="  Western  "  , Price = 3.99 m  });} 

Code first migrations calls the seed method after each migration (that is, the update-database method is called in the Package Manager Console). This method updates the rows in the database and inserts new rows if no rows exist.

Re-generate the following project before proceeding to the next step. Otherwise, the following steps will fail.

In the Package Manager Console window, enter the command "Add-migration initial" to create the initial migration. The name "initial" only starts with it and is used to name the created Migration file.

CODI first migrations creates another class file (named after {timestamp} _ initial. CS) in the migrations folder. This class contains the code for creating the database mode. This file is prefixed with a timestamp to facilitate sorting. Check the content in the {timestamp} _ initial. CS file, which contains instructions for creating a movies table for movie dB. When we use the following command to create a database, {timestamp} _ initial. the code in the CS file will be executed to create the database mode, and then the seed method will be called to add test data for the database.

If you see an error saying that the database table already exists and cannot be created repeatedly, it is probably because you have run the program before executing the update-database command after deleting the database. In this case, re-delete the movies. MDF file and run the update-database command again. If an error is still reported, delete the files in the migrations folder and the folder, and repeat the steps at the beginning of the article.

Run the application and navigate to/movies. The data added in the seed method is displayed.

Adds a rating attribute to the movie object class.

Let's start adding a rating attribute for the movie class. Open the models \ movie. CS file and add the rating attribute. The complete movie code is as follows:

 Public   Class  Movie {  Public   Int Id { Get ; Set  ;}  Public  String Title { Get ; Set  ;}  Public Datetime releasedate { Get ; Set  ;}  Public   String Genre { Get ; Set  ;}  Public   Decimal Price { Get ; Set  ;} 

Public StringRating {Get;Set

 
;}}

Regenerate the following items.

Now we have updated the model class. Next we will update the following \ views \ movies \ index. cshtml and \ views \ movies \ create. cshtml view templates to display the newly added attributes.

Open, views, movies \ index. add <TH> rating </Th> to the price column of the cshtml file. then add a <TD> near the end of the template file to render @ item. the value of rating. The following is the content of the updated index. cshtml file.

@ Model ienumerable <mvcmovie. Models. Movie>@ {Viewbag. Title = "  Index  "  ;} <H2> index </H2> <p> @ Html. actionlink (  "  Create new  " , "  Create  "  ) </P> <Table> <tr> <TH> @ Html. displaynamefor (Model =>Model. Title) </Th> <TH> @ Html. displaynamefor (Model => Model. releasedate) </Th> <TH> @ Html. displaynamefor (Model => Model. Genre) </Th> <TH> @ Html. displaynamefor (Model => Model. Price) </Th>

<TH>

@ Html. displaynamefor (Model

=>Model. rating)</Th>

     @ foreach (  var  item  in   model) {    @ HTML. displayfor (modelitem =>  item. title)    @ HTML. displayfor (modelitem =>  item. releasedate)    @ HTML. displayfor (modelitem =>  item. genre)    @ HTML. displayfor (modelitem =>  item. price)   

<TD>

 
@ Html. displayfor (modelitem

=>Item. rating)</TD>

<TD> @ Html. actionlink (  "  Edit  " , "  Edit  " , New {Id = item. ID}) |@ Html. actionlink (  "  Details  " , "  Details  " , New {Id = item. ID}) | @ Html. actionlink (  "  Delete  " , "  Delete  " ,New {Id = Item. ID }) </TD> </tr> } </Table>

Next, open the \ views \ movies \ create. cshtml file and add the following tag near the end of the form. When a new movie is created, a text box will be rendered so that you can specify a rating.

<DivClass="Editor-label">@ Html. labelfor (Model=>Model. rating)</Div> <DivClass="Editor-field">@ Html. editorfor (Model=>Model. rating) @ html. validationmessagefor (Model=>Model. rating)</Div>

Run the program and navigate to/movies. You will see the following error:

The reason for this error is that the structure of the movie object class is inconsistent with that of the movie table in the database, and there is no rating field in the database.

There are several ways to solve this problem:

1. Enable the Entity Framework to automatically delete and recreate the database based on the new model class. It is very convenient to develop on a test database, allowing you to synchronize databases and models very quickly. The disadvantage is that you will lose all the data in the database-so you cannot use this method in the database in the production environment! Using an initiator to automatically populate test data (the previously mentioned seed method) is very effective during development. For more information about the Entity Framework database initialization tool, see ASP. net mvc/Entity Framework tutorial of Tom Dykstra.

2. The structure of the existing database table is changed to be consistent with that of the model. Some of the data will not be lost. You can manually modify or write some scripts to modify the data.

3. Use code first migrations to update the database structure.

In this article, we use code first migrations.

Modify the seed method to provide a value for the new column. Open the migrations \ configuration. CS file and assign a value to the rating attribute for each movie object.

  New   movie {Title  = "   When Harry Met Sally  "  , releasedate  = datetime. parse ( "  1989-1-11  "   ), genre  =  "  romantic comedy  "  , rating  =  "  G  "  , price  =  7.99 m   },  

Regenerate the project and open the Package Manager Console window and enter the following command: Add-migration addratingmig

The add-migration Command tells the migration framework to check the movie entity class and the existing Movie Database, and create the required Code to ensure that the database structure is consistent with the model. Addratingmig is a random name used to name the migration file. It is very helpful to use a meaningful name.

After this command is executed, open the file defining the new dbmigration class. In the UP method, you will see the code for adding a new column to the database:

 Public   Partial   Class  Addratingmig: dbmigration {  Public   Override   Void  Up () {AddColumn (  "  DBO. Movies  " , "  Rating  " , C => C. String ());}  Public   Override   Void  Down () {dropcolumn (  "  DBO. Movies  " , "  Rating  "  );}} 

Regenerate the project and enter the "Update-Database" command in the Package Manager Console window.

The following is the output of the Package Manager Console window (the timestamp before addratingmig will be different)

Run the program again and navigate to/movies. We will see the newly added field.

Click the create new link to add a new movie. Note that we can enter a value for the rating field.

Click Create. The new Movies list is as follows:

You can also add the rating field to the view templates of edit, details, and searchindex.

At this time, if you enter the update-database command again in the Package Manager Console window, nothing will happen, because the database table structure is consistent with the model.

In this section, we know how to modify the model object and maintain consistency between the database and the model. We also introduced a method to add some test data to the new database. Next, let's take a look at how to add rich logic verification rules for the model class.

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.