ASP. NET mvc4.0 Getting Started Guide-add fields to the movie model and database table

Source: Internet
Author: User
Tags visual studio 2010

In this section, you will use the Entity Framework code first migration function to modify the model class and apply the modification to the database.

By default, when you use the Entity Framework code to automatically create a database, as you did before this tutorial, the code first adds a table to the database, to help track whether the database architecture is a synchronized model class. If they are not synchronized, the Entity Framework throws an error. This makes it easier to track and locate problems during early development. Otherwise, you may find hidden errors during runtime.

Create Code first migration for Model Modification
If you are using Visual Studio 2012, double-click the movies. MDF file in Solution Explorer to open the database tool. Visual Studio express for Web displays "Database Resource Manager" and visual studio2012 displays "server resource manager". If you are using Visual Studio 2010, use the SQL Server Object Resource Manager.

In database tools, right-click moviedbcontext and choose Delete.
Go back to solution Resource Manager. Right-click the movies. MDF file and choose delete from the shortcut menu.

Note: This may seem confusing. In fact, the first step is to delete the database link. The pop-up deletion confirmation prompt also describes this, the second step is to delete the database files in solution manager.

Generate the application and confirm that there is no compilation error.
In the vs2012 tool menu, click "Program Package Manager"-"Package Manager Console"
Enter "enable-migrations-contexttypename mvcmovie. Models. moviedbcontext" after the PM> mark in the console"
 
Output the following information:
PM> enable-migrations-contexttypename mvcmovie. Models. moviedbcontext
Checking whether the target of the context is an existing database...
Code first migration is enabled for the project mvcmovie.
PM>

The preceding enable-migrations command creates a new migrations folder and the configuration. CS file is created under this directory.
Use Visual Studio to open the configuration. CS file. Use the following code to replace the seed method:

Protected override void seed (mvcmovie. models. moviedbcontext context) {context. movies. addorupdate (M => M. name, new movie {name = "youth's fantastic drifting tour", date = datetime. now}, new movie {name = "1942", date = datetime. now}, new movie {name = "King's Feast", date = datetime. now });}

The above code needs to import the namespace using mvcmovie. models into the class;

The code first migration mechanism calls the seed method after each migration. If row data exists, the method updates existing data. If no row data exists, the method inserts data.

Press Ctrl + Shift + B to generate the project. (If you do not perform this operation, the subsequent steps will fail)

The next step is to create the dbmigration class to initialize the migration. The migration creates a new database, which is also the reason for deleting the database file in the previous step.
In the Package Manager Console window, enter the command "Add-migration initial" to create the initial migration. Initial can be any name used to identify the created initial file. The console output is as follows:

PM> Add-migration initial
The base is being built for the migration "initial.
The designer code of this migration file contains a snapshot of the current Code first model. This snapshot will be used to calculate the changes to the Model during the next build of the migration base. If you make other changes to the model that you want to include in this migration, you can re-run "Add-migration 201212060747227_initial" to re-build the base shelf.
PM>

The code first migration mechanism creates another class file in the migrations folder. The file name is timestamp + underline + initial. CS, for example, 201212060747227_initial.cs. This class contains the code for creating the database architecture. Migration file names are sorted by timestamp. View the file, including instructions for creating a movie library table. When you update a database, this class is executed to create a database architecture. Then, the seed method is executed and the test data is added.

In the Package Manager Console window, type the "Update-Database" command to create a database and execute the seed method.
PM> Update-Database
Specify the "-verbose" flag to view the SQL statements applied to the target database.
Application code-based migration: [201212060747227_initial].
Applying code-based migration: 201212060747227_initial.
Running the seed method.
PM>

If a table cannot be created due to an error that already exists, it is likely that after you delete the database, you run the application before executing Update-database (re-compile the program and automatically create the database ). In this case, delete the database file again and run the update-database command. If an error persists, delete the migrations directory and content and restart this tutorial.

Run the application and navigate to the/movies address. The seed data is displayed.

Note: The seed data here actually refers to some test data or system initialization data added after some database tables are created, such as system parameters and department root directories.

Add evaluation attributes to the movie Model

Adds a rating attribute for an existing video category. Open the models \ movie. CS file and add the rating attribute as follows:
Public String rating {Get; set ;}

Compile the application by generating the menu or pressing CTRL + Shift + B.
Now that you have updated the model class, you also need to update the \ views \ movies \ index. cshtml and \ views \ movies \ create. cshtml view templates.
Open the \ views \ movies \ index. cshtml file and add the column title <TH> rating </Th> after the price column. Add the <TD> column label near the end of the template.
The create view is also modified, which is not described in detail here.

Now you have updated the program code to support the new evaluation attributes. Run the program and navigate to/movies. You will find the following error:

The model that supports the "moviedbcontext" context has been changed after the database is created. Consider using code first to migrate an update database (http://go.microsoft.com/fwlink? Linkid = 238269 ).

This error occurs because you have updated the movie model class in the program, which is different from the structure of the movie database table in an existing database (there is no rating column in the database movie table ).

To solve this problem, you can:
1. Enable Entity Framework to automatically delete and recreate common databases based on the new model class architecture. This method is very suitable for dynamic development of test data. It allows you to quickly evolve the model and database table structure. However, the disadvantage is that the existing data in the current database will be lost-so you do not want to use this method on the production database. It is usually an efficient way to develop applications to automatically generate databases by using the initialization tool on the test database. For more information about the Entity Framework initializer, see ASP. net mvc/Entity Framework tutorial written by Tom Dykstra.
2. explicitly modify the existing database architecture so that it matches the model class. The advantage of this method is that the existing data is retained. You can manually or create a database script to make changes.
3. Use code first migration to update the database architecture

In this course, we will use the third method mentioned above, that is, code first migration.
Update the seed method to provide values for the newly added columns. Open the migrations \ configuration. CS file and add the rating value for each movie object.
Generate a solution, open the Database Manager Console window, and enter the following command Add-migration addratingmig
The add-migration Command tells the migration framework to compare the results of the current model with the database table, and generate the necessary code to adapt the database table to the model. The addratingmig name can be arbitrary, but it is only the identifier of the migration file. Using meaningful names helps with migration operations.
After the command is executed, Visual Studio opens the class file and creates a new dbmigration class. In the UP method, you can see the code for creating a 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");        }    }

 

Generate a solution. In the Database Manager Console window, enter the "Update-Database" command.
PM> Update-Database
Specify the "-verbose" flag to view the SQL statements applied to the target database.
Application code-based migration: [201212060835020_addratingmig].
Application code-based migration: 201212060835020_addratingmig.
Running the seed method.
PM>
Run the application and navigate to/movies. You will see the newly added rating column.
Similarly, you need to modify the edit and delete views and add the rating attribute.
You can enter the "Update-Database" command in the Database Manager Console again and find that the modification is not applied because the current database table structure matches the model.

In this section, you learned how to modify Model objects and maintain synchronization with databases. I also learned how to create a database with sample data. Next we will learn how to add verification logic for the model class to make the business rule take effect.

Note: This article is rather fragmented. Here, we will summarize how to use the Migration Feature provided by the Code to ensure automatic matching between the model and the database, run the following commands in the library Package Manager in sequence:
1. Enable migration: Enable-migrations-contexttypename mvcmovie. Models. moviedbcontext
2. Create the initial state: Add-migration initial
3. automatically compare the differences to generate a migration class: Add-migration addratingmig
4. migrate the application to the database: Update-Database
In the actual project development or maintenance process, due to business requirements or design changes, you often need to add or delete fields to the database table. In the case of multiple project teams working together, it is easy to omit the modification to the database, and the migration function ensures this well. It automatically records the changes to the database table for model changes.

 

 

Navigation of all articles in this tutorial

 

This series contains 10 articles translated from ASP. net mvc4 official tutorial, due to the concise description of this series of articles, the length is moderate, from an example to explain, the full text finally completed a small system for managing movies, very suitable for beginners ASP.. Net mvc4.

 

The original article is for 9 articles, and the translator splits 6th of them into 2

 

1. Introduction to ASP. NET mvc4

 

· Original address: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/intro-to-aspnet-mvc-4

 

· Address: http://www.cnblogs.com/seawaving/archive/2012/12/03/2800210.html

 

2. Add a controller

 

· Original address: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-controller

 

· Address: http://www.cnblogs.com/seawaving/archive/2012/12/04/2801949.html

 

3. Add a view

 

· Original address: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-view

 

· Address: http://www.cnblogs.com/seawaving/archive/2012/12/04/2801988.html

 

4. Add a model

 

· Original address: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-model

 

· Address: http://www.cnblogs.com/seawaving/archive/2012/12/05/2803012.html

 

5. Access the data model from the Controller

 

· Original address: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/accessing-your-models-data-from-a-controller

 

· Address: http://www.cnblogs.com/seawaving/archive/2012/12/05/2803429.html

 

6. view the Edit Method and edit View

 

· Original address: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/examining-the-edit-methods-and-edit-view

 

· Address: http://www.cnblogs.com/seawaving/archive/2012/12/05/2804100.html

 

Http://www.cnblogs.com/seawaving/archive/2012/12/06/2804590.html

 

7. Add fields for the movie model and database table

 

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

 

· Address: http://www.cnblogs.com/seawaving/archive/2012/12/06/2805401.html

 

8. Add verification for the model

 

· Original address: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-validation-to-the-model

 

· Address: http://www.cnblogs.com/seawaving/archive/2012/12/06/2806322.html

 

9. view the detail and delete Methods

 

· Original address: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/examining-the-details-and-delete-methods

 

· Address: http://www.cnblogs.com/seawaving/archive/2012/12/10/2811064.html

 

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.