In this section, you will use the Entity Framework code-ahead migration feature to modify the model class and apply the modifications to the database.
By default, when you use Entity Framework code to automatically create a database, as you did earlier in this tutorial, the code first adds a table to the database to help track whether the database schema is synchronous and the model class is generated. If they are not synchronized, the Entity Framework throws an error. This makes it easier to track discovery problems early in development, or you may find cryptic errors at run time.
Establish code-first migration for model modifications
If you are using Visual Studio 2012, in Solution Explorer, double-click the Movies.mdf file to open the database tool. The visual Studio Express for Web will display the Database Explorer, and visual Studio2012 will display the Server Explorer. If you are using Visual Studio 2010, use SQL Server Object Explorer.
In the database tool, right-click on the Moviedbcontext and select Delete.
Go back to Solution Explorer. Right-click on the movies.mdf file and select Delete.
Translator Note: It seems confusing here, in fact, the first step actually performed is to delete the database link, the pop-up deletion confirmation Prompt also illustrates this point, the second step is to really delete the database file in the solution manager.
Build the application and verify that there are no compilation errors.
In the VS2012 Tools menu, click the "library Package Manager"-"Package Manager" console
After the pm> tag in the console, enter "Enable-migrations-contexttypename MvcMovie.Models.MovieDbContext"
Output the following information:
Pm> Enable-migrations-contexttypename MvcMovie.Models.MovieDbContext
Checking whether the target of the context is an existing database ...
The Code first migration has been enabled for Project Mvcmovie.
Pm>
The enable-migrations command above creates a new migrations folder and creates a Configuration.cs file in that directory.
Open the Configuration.cs file by using Visual Studio. Replace the seed method content with the following code:
protected override void Seed (MvcMovie.Models.MovieDbContext context) { context. Movies.addorupdate ( m = m.name, new Movie {name = "The Fantasy Rafting trip for Youth", Date=datetime.now}, new movie {name = "one 942 ", date = DateTime.Now}, new Movie {Name =" Feast of the Kings ", date = DateTime.Now} );
The above code requires a class to import namespaces using Mvcmovie.models;
The code-First migration mechanism calls the seed method after each migration, and if there is row data, the method updates the existing data and if it does not, the method inserts the data.
Press Ctrl+shift+b to build the project (if this build operation is not performed here, 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 why you deleted the database files in the previous steps.
In the Package Manager Console window, enter the command "Add-migration Initial" to create the initial migration. Where initial can be any name used to identify the initial file that was created. The console output is as follows:
Pm> add-migration Initial
Scaffolding is being built for migrating "Initial".
The designer code for this migration file contains a snapshot of the current Code first model. This snapshot is used to calculate changes to the model the next time the migration scaffolding is built. If you make other changes to the model that you want to include in this migration, you can re-build the scaffolding by running Add-migration 201212060747227_initial again.
Pm>
Code-First migration mechanism creates another class file under the Migrations folder, with the file name Timestamp + underscore + Initial.cs, such as 201212060747227_initial.cs, which contains the code to create the database schema. Migration file names are preset as timestamps to help sort. View the file, which contains a description of the Create Movie library table. When you update the database, the class is executed and the database schema is created. The seed method is then executed and the test data is added.
In the Package Manager Console window, type the "update-database" command to create the database and execute the seed method.
Pm> Update-database
Specify the "-verbose" tag to view the SQL statements applied to the target database.
Applying code-based migration: [201212060747227_initial].
Applying code-based migration: 201212060747227_initial.
The Seed method is running.
Pm>
If you encounter an error that already exists in the table and cannot be created, it is likely that after you have deleted the database, you run the application (recompiling the program and automatically created the database) before executing update-database. In this case, delete the database file again and execute the update-database command. If you still get the error, delete the migrations directory and contents and start the tutorial again.
Run the application and navigate to the/movies address. The seed data shows up.
Note: The seed data here actually refers to some of the test data added after the creation of the library table or system initialization data, such as system parameters, Department root directory, etc.
Add evaluation attributes to the movie model
Adds an evaluation attribute to the existing movie class. Open the Models\movie.cs file and add the rating property as follows
public string Rating {get; set;}
Compile the application through the Build menu or the Ctrl+shift+b shortcut key.
Now that you have updated the model classes, 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 heading <th>Rating</th> after the price column. Then add <td> column labels near the end of the template.
The CREATE view also makes the appropriate modifications, which are no longer described in detail.
Now you have updated the program code to support the new evaluation properties. Run the program and navigate to/movies, and you will find the following error:
Models that support the "Moviedbcontext" context have changed since the database was created. Consider migrating the update database (http://go.microsoft.com/fwlink/?LinkId=238269) using Code first.
This error occurs because you updated the movie model class in your program to be different from the movie library table structure in the existing database (there is no rating column in the Database movie table).
There are several ways to resolve this issue:
1. Make the Entity framework automatically delete and re-common databases based on the new model class schema. This method is well suited for developing dynamic development on test data, and enables you to quickly evolve models and database table structures. The downside, however, is that data that already exists in the current database is lost-so you don't want to use this approach on the production database. Using an initializer on a test database to automatically generate a database is often a way to develop an application efficiently. For more information about the Entity Framework initializer, see the ASP. NET mvc/entity Framework tutorial written by Tom Dykstra.
2. Explicitly modify the existing database schema so that it matches the model class. The advantage of this approach is that the existing data is preserved. You can make changes by manually or by creating a database script.
3. Updating the database schema by using code-first migration
In this lesson, we will use the third approach described above, i.e. code-first migration
Update the seed method so that it provides values for the new columns. Open the Migrations\configuration.cs file to increase the rating value for each movie object.
Build the solution, and then open the Library Manager Console window and enter the following command add-migration Addratingmig
The Add-migration command tells the migration framework to compare the differences between the current model and the library table results, and generates the necessary code to fit the library table with the model. The Addratingmig name can be arbitrary, just the identifier of the migrated file. Use meaningful names to help with migration operations.
When the command finishes, Visual studio opens the class file, creates a new Dbmigration class, and in its 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 the solution, and the Library Manager console window enters the "update-database" command.
Pm> Update-database
Specify the "-verbose" tag to view the SQL statements applied to the target database.
Applying code-based migration: [201212060835020_addratingmig].
Applying code-based migration: 201212060835020_addratingmig.
The Seed method is running.
Pm>
Run the application, navigate to/movies, and you will see the new rating column
Again, you need to modify the edit and delete views to add the rating property.
You can enter the "update-database" command again in the Library Manager console and find that no modifications have been applied because the current database table structure matches the model.
In this section, you learned how to modify a model object and keep it synchronized with the database. You also learned how to create a database with sample data. Below we will learn how to add validation logic to the model class to bring the business rules into effect.
Translator Note: This article is relatively fragmented, in this summary, to use the migration function provided by the code to ensure that the model and database automatic matching, you need to execute the following command in the Library Package Manager:
1. Enable the migration feature: Enable-migrations-contexttypename MvcMovie.Models.MovieDbContext
2. Establishment of the initial state: Add-migration Initial
3. Automatic comparison Variance Generation Migration class: Add-migration Addratingmig
4. Apply the migration to the database: Update-database
In the actual project development process or maintenance process, because of business requirements or design changes, often need to the library table and delete fields, in the project team in the development of collaborative mode, it is easy to omit the modification of the database, and the migration function is very good to ensure this, "automatic" Changes to the library table are recorded for the model changes.
"Go", ASP. NET MVC4.0 Official tutorial eight--add fields to the movie Model and library table