asp.net MVC4 Introductory Tutorial (vii): Adding new fields to movie tables and models _ self-study process

Source: Internet
Author: User
Tags actionlink visual studio 2010

In this section, you will use the entity Framework Code A to implement the operations on the model class. So that these operations and changes can be applied to the database.

By default, as you did in previous tutorials, using the Entity Framework code first to automatically create a database, the table that code first adds to the database will help you keep track of whether the database is synchronized with the model classes it generates. If they are not synchronized, the Entity framework throws an error. This is very handy for you to discover errors at development time, or you may find this problem at run time. (by an obscure error message, the problem was found.) )

Set the Code migrations for changes to the object model

If you are using Visual Studio 2012, double-click movies.mdffrom Solution Explorer to open the database Tools. Visual Studio Express for Web will display Database Explorer, and Visual Studio 2012 will display server Resource Manager. If you are using Visual Studio 2010, use SQL Server object Resource Manager.

In Database Tools (Database Explorer, Server Explorer, or SQL Server Object Explorer), right-click Moviedbcontext and select Delete to delete the movie database.

Return to Solution Explorer. Right-click on the movies.mdf file and select Delete to delete the movie database.

Build application to ensure that there are no compilation errors.

From the Tools menu, click Library Package Manager, and then click the Package Manager console.

Enter "Enable-migrations–contexttypename MvcMovie.Models.MovieDBContext" at the pm> prompt in the Package Manager console window.

(as shown above) The Enable-migrations command creates a Configuration.cs file in the Migrations folder.

Open the Configuration.cs file in Visual Studio. Replace the seed method in the Configuration.cs file with the following code:

protected override void Seed (MvcMovie.Models.MovieDBContext context) {context 
  . Movies.addorupdate (
    i => i.title, 
    new Movie {Title = "when Harry Met Sally", ReleaseDate = DateTime.Parse ("198 9-1-11 "), genre =" romantic comedy ", Price = 7.99M}, 
    new Movie {Title =" Ghostbusters ", ReleaseDate = Datetime.pars E ("1984-3-13"), genre = "comedy", Price = 8.99M}, 
    new Movie {Title = "Ghostbusters 2", ReleaseDate = DateTime.Parse ( "1986-2-23"), genre = "comedy", Price = 9.99M}, 
    new Movie {Title = "Rio Bravo", ReleaseDate = DateTime.Parse ("1959-4 -15 "), genre =" Western ", Price = 3.99M}
  ); 

Right-click on the red wavy line that appears below the movie and select Resolve and click Using Mvcmovie.models;

After doing so, the following using statement is added:

Using Mvcmovie.models;

Each time code-migrations calls the seed method (that is, calls Update-database in the Package Manager console), and the call updates the row: Updates the rows that have been inserted, or inserts the nonexistent rows.

Press Ctrl-shift-b to build the project. (If this build is unsuccessful, the following steps will fail.) )

The next step is to create a dbmigration class for initializing the database migration. This migration class will create a new database, which is why you deleted the Movie.mdf file in the previous steps.

In the Package Manager Console window, enter the add-migration Initial command to create the initial migration. The name "Initial" is any name that is used to create the migrated file.

Code migrations will create another class file in the Migrations folder (file name: {datestamp}_initial.cs ), which will create a schema for the database. The migration file name uses a timestamp as a prefix to help sort and find. View the {datestamp}_initial.cs file, which contains instructions for creating a movie table for the movie Database. When you update the database, the{datestamp}_initial.cs file is run and the DB schema is created. The seed method then runs to populate the test data for DB.

In the Package Manager console, enter the command "Update-database", create the database, and run the seed method.

If you receive an error that the table already exists and cannot be created, it may be because you have deleted the database and you ran the application before executing update-database. In this case, delete the Movies.mdf file again, and then retry the Update-database command. If you still encounter an error, delete the Migration folder and its contents, and then redo it from the beginning. (That is, delete the Movies.mdf file and then Enable-migrations)

Run the application, and then browse the Url/movies seed data as shown below:

To add a rating attribute for a movie model

Add a new rating property to the existing movie class. Open the Models\movie.cs file and add the following rating properties:

public string Rating {get; set;}

The complete movie class 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 string Rating {get; set;} 
}

Build application Build>build Move or ctrl-shift-b.

Now that you have updated the model class, you will also need to update the \views\movies\index.cshtml and \views\movies\create.cshtml view templates, So that the new rating property can be displayed in the browser.

Open the \views\movies\index.cshtml file and add <th>Rating</th> column headers after the price column. Then add a <td> column to display the @item. The value of the rating. The following is an updated index.cshtml View Template:

@model ienumerable<mvcmovie.models.movie> @{viewbag.title = "Index";}
     

Next, open the \views\movies\create.cshtml file and add the following code near the end of the form label. You can specify a movie level when you create a new movie.

<div > @Html. labelfor (model => model. Rating) </div>
<div > @Html. editorfor (model => model. Rating) @Html. Validationmessagefor (model => model. Rating) </div>

You have now updated the application code to support the new rating property.

Run the application now, and then browse to the /movies URL. However, when you do so, you will see one of the following error messages:

You see this error now because in the application the newest movie model class is different from the schema of the existing Database movie table. (There are no rating columns in the database table.) )

We will use code first migrations to solve this problem.

Update the seed method so that it can provide a value for the new column. Open the Migrations\configuration.cs file and add the Rating field to each object in the movie.

New Movie
{
  Title = "When Harry Met Sally",
  releasedate = DateTime.Parse ("1989-1-11"),
  genre = "Romantic Comedy ",
  Rating =" G ", price
  = 7.99M
},

Build solution, and then 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 current movie model with the current movie DB schema and create the necessary code to migrate the database to the new model. Addratingmig is an arbitrary filename parameter that is used to name the migration file. It will help make the migration step a meaningful name.

When the command completes, open the class file with Visual Studio, new inherits from the definition of the Dbmigration class, and in the up method, you can see the code that creates the new column:

public partial class Addratingmig:dbmigration
{public
  override void Up ()
  { 
    addcolumn ("dbo. Movies "," Rating ", C => c.string ()); 
  }
  public override void Down ()
  {
    dropcolumn ("dbo.") Movies "," Rating ");
  }

Build solution, and then enter the "update-database" command in the Package Manager console window.

The following picture shows the output of the Package Manager Console window (the ADDRATINGMIG prefix timestamp will vary).

Rerun the application, and then browse the/movies URL. You can see the new rating field.

Click the createnew link to add a new movie. Note that you can add a rating to your movie.

Click Create. New movies, including ratings, will be displayed in the list of movies:

In addition, you should add the Rating field to the edit, details, and searchindex view templates.

You can enter the "update-database" command again in the Package Manager console window, and there will be no new changes because the database schema and the model class are now matched.

In this section, you see how to modify a model object and always keep it synchronized with the database schema. You also learned the example of using the populate sample data to create a new database, which you can try again and again. Next, let's look at how to add rich validation logic to the model class and perform some forced business rule validation on the model class.

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.