In this section, you will use Entity Framework Code First to perform model class operations. So that these operations and changes can be applied to the database.
By default, as you did in the previous tutorial, Entity Framework Code First is used to automatically create a database, and Code First is the table added to the database, it will help you track whether the database is synchronized with the model class generated from it. If they are not synchronized, Entity Framework will throw an error. This is very convenient for you to find errors during development, or you may find this problem only during runtime. (This problem was discovered only by an obscure error message .)
Set Code First Migrations for changes to the object model
If you are using Visual Studio 2012, double-clickMovies. mdfTo open the database tool. Visual Studio Express for Web displays the database resource manager, and Visual Studio 2012 displays the server resource manager. If you are using Visual Studio 2010, use the SQL Server Object Resource Manager.
In the database tool database resource manager, Server resource manager, or SQL Server Object Resource Manager, right-clickMovieDBContext
And selectDeleteTo delete the Movie Database.
650) this. width = 650; "style =" border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-right -: "title =" clip_image001 "border =" 0 "alt =" clip_image001 "width =" 439 "height =" 352 "src =" http://www.bkjia.com/uploads/allimg/131228/115R62112-0.png "/>
Return to solution Resource Manager. Right-click the Movies. mdf file and selectDeleteTo delete the Movie Database.
650) this. width = 650; "style =" border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-right -: "title =" clip_image002 "border =" 0 "alt =" clip_image002 "width =" 345 "height =" 447 "src =" http://www.bkjia.com/uploads/allimg/131228/115R64147-1.png "/>
Build the application to ensure there are no compilation errors.
SlaveToolsClickLibrary Package ManagerAnd then clickPackage Manager Console.
650) this. width = 650; "style =" border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-right -: "title =" clip_image003 "border =" 0 "alt =" clip_image003 "width =" 607 "height =" 292 "src =" http://www.bkjia.com/uploads/allimg/131228/115R635b-2.png "/>
InSoftware Package Manager ConsoleEnter "Enable-Migrations-ContextTypeName MvcMovie. Models. MovieDBContext" at the PM> prompt in the window ".
650) this. width = 650; "style =" border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-right -: "title =" clip_image004 "border =" 0 "alt =" clip_image004 "width =" 740 "height =" 348 "src =" http://www.bkjia.com/uploads/allimg/131228/115R61010-3.png "/>
As shown above)Enable-MigrationsCommand will create a Configuration. cs file in the Migrations folder.
650) this. width = 650; "style =" border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-right -: "title =" clip_image005 "border =" 0 "alt =" clip_image005 "width =" 279 "height =" 332 "src =" http://www.bkjia.com/uploads/allimg/131228/115R64K7-4.png "/>
Open the Configuration. cs file in Visual Studio. Replace the Seed method in the Configuration. cs file with the following code:
?
Right-click the red wave line that appears under Movie and selectResolveThen clickUsingMvcMovie. Models;
650) this. width = 650; "style =" border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-right -: "title =" clip_image006 "border =" 0 "alt =" clip_image006 "width =" 606 "height =" 390 "src =" http://www.bkjia.com/uploads/allimg/131228/115RB9E-5.png "/>
After doing so, the following using statement will be added:
?
Each Code First Migrations calls the Seed method, which is called in the Package Manager Console.Update-database), And the call will update the row: update the inserted row, or insert the non-existing row.
PressCTRL-SHIFT-BComeBuild project.If this Build fails, the following steps will fail .)
The next step is to createDbMigration
Class, used to initialize database migration. This migration class will create a new database, which is why you want to delete it in the previous step.movie.mdf
File.
InSoftware Package Manager ConsoleIn the window, enter the "add-migration Initial" command to create the Initial migration. The "Initial" name is arbitrary and is the name used to create the migration file.
650) this. width = 650; "style =" border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-right -: "title =" clip_image007 "border =" 0 "alt =" clip_image007 "width =" 725 "height =" 346 "src =" http://www.bkjia.com/uploads/allimg/131228/115R61B2-6.png "/>
Code First Migrations will create another class file name in the Migrations Folder:{DateStamp} _ Initial. cs), The Code contained in this class will create the Schema of the database. The migration file name uses the timestamp as the prefix to help sort and search. View{DateStamp} _ Initial. csFile, which contains instructions for creating a movie table for the movie database. When you update the database,{DateStamp} _ Initial. csThe file will be run and the Schema of the database will be created. ThenSeedThe method is run to fill in the test data of the DB.
InSoftware Package Manager ConsoleRun the "update-database" command to create and run the database.SeedMethod.
650) this. width = 650; "style =" border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-right -: "title =" clip_image008 "border =" 0 "alt =" clip_image008 "width =" 714 "height =" 348 "src =" http://www.bkjia.com/uploads/allimg/131228/115R640K-7.png "/>
If you receive an error that the table already exists and cannot be created, it may be because you have deleted the database andupdate-database
Previously, you ran the application. In this case, delete the Movies. mdf file again and try again.update-database
Command. If you still encounter an error, delete the Migration folder and its content, and redo it from the beginning. Delete the Movies. mdf file, and then Enable-Migrations)
Run the application, and then browse the URL/Movies Seed data to display the following:
650) this. width = 650; "style =" border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-right -: "title =" clip_image009 "border =" 0 "alt =" clip_image009 "width =" 752 "height =" 593 "src =" http://www.bkjia.com/uploads/allimg/131228/115RCP9-8.png "/>
Add rating attributes for the Video Model
To existingMovie
Class to add a newRating
Attribute. Open the Models \ Movie. cs file and add the followingRating
Attribute:
public string Rating { get; set; }
CompleteMovie
Class:
?
Build ApplicationBuild>Build MoveOr CTRL-SHIFT-B.
Now you have updatedModel
Class, you also need to update\ Views \ Movies \ Index. cshtmlAnd\ Views \ Movies \ Create. cshtmlView template to display the newRating
Attribute.
Open\ Views \ Movies \ Index. cshtmlFile, inPriceAdd after Column<th>Rating</th>
. Then add<td>
Column to display@item.Rating
. Below is the updatedIndex. cshtmlView template:
?
Next, open\ Views \ Movies \ Create. cshtmlFile, and add the following code near the end of the form tag. You can specify a level when creating a new movie.
?
Now you have updated the application code to support the newRating
Attribute.
Run the application and then browse/Movies. However, when you do this, you will see one of the following error messages:
650) this. width = 650; "style =" border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-right -: "title =" clip_image010 "border =" 0 "alt =" clip_image010 "width =" 458 "height =" 385 "src =" http://www.bkjia.com/uploads/allimg/131228/115R620A-9.png "/>
650) this. width = 650; "style =" border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-right -: "title =" clip_image011 "border =" 0 "alt =" clip_image011 "width =" 626 "height =" 587 "src =" http://www.bkjia.com/uploads/allimg/131228/115R610M-10.png "/>
You can see this error because in the application, the latestMovie
Model class and existing databaseMovie
The table Schema is different. Database table, noRating
Column .)
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 of the video.
new Movie
{
Title = "When Harry Met Sally",
ReleaseDate = DateTime.Parse("1989-1-11"),
Genre = "Romantic Comedy",
Rating = "G",
Price = 7.99M
},
Build the solution, and then openSoftware Package Manager ConsoleWindow, and enter the following command:
add-migration AddRatingMig
add-migration
Command tells migration framework to check the current movie model and the current movie DB Schema and create the necessary code to migrate the database to the new model. AddRatingMig is an arbitrary file name parameter used to name a migration file. It will help make the migration step a meaningful name.
After the command is complete, use Visual Studio to open the class file, new inherited fromDbMIgration
Class, andUp
Method, you can see the code for creating a new column:
?
Build the solution, and thenPackage Manager ConsoleEnter the "update-database" command in the window.
The image below showsPackage Manager ConsoleThe prefix timestamp of the output AddRatingMig window will be different ).
650) this. width = 650; "style =" border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-right -: "title =" clip_image012 "border =" 0 "alt =" clip_image012 "width =" 659 "height =" 104 "src =" http://www.bkjia.com/uploads/allimg/131228/115RCR2-11.png "/>
Run the application again and then browse the/Movies URL. You can see the new rating field.
650) this. width = 650; "style =" border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-right -: "title =" clip_image013 "border =" 0 "alt =" clip_image013 "width =" 794 "height =" 605 "src =" http://www.bkjia.com/uploads/allimg/131228/115RB325-12.png "/>
ClickCreateNewLink to add a new movie. Note: you can add a rating for a movie.
650) this. width = 650; "style =" border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-right -: "title =" clip_image014 "border =" 0 "alt =" clip_image014 "width =" 490 "height =" 746 "src =" http://www.bkjia.com/uploads/allimg/131228/115R63215-13.png "/>
ClickCreate. New movies, including ratings, will be displayed in the movie list:
650) this. width = 650; "style =" border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-right -: "title =" clip_image015 "border =" 0 "alt =" clip_image015 "width =" 666 "height =" 688 "src =" http://www.bkjia.com/uploads/allimg/131228/115R61931-14.png "/>
In addition, you shouldRating
Fields are added to the view template for editing, details, and SearchIndex.
You canPackage Manager ConsoleIf you enter the "update-database" command in the window, no new changes will occur, because the database Schema and model class are currently matched.
In this section, you can see how to modify the model object and keep it synchronized with the database Schema. You have also learned how to create a database by filling in sample data. You can try again and again. Next, let's take a look at how to add rich verification logic to the model class and perform some mandatory business rule verification on the model class.
Bytes --------------------------------------------------------------------------------------------------------------------
Note:
This series contains nine 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. Nine articles:
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/powertoolsteam/archive/2012/11/01/2749906.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/powertoolsteam/archive/2012/11/02/2751015.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/powertoolsteam/archive/2012/11/06/2756711.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/powertoolsteam/archive/2012/12/17/2821495.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/powertoolsteam/archive/2013/01/11/2855935.html
6. Verify the editing method and 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/powertoolsteam/archive/2013/01/24/2874622.html
7. Add new fields to the movie table and Model
· 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://powertoolsteam.blog.51cto.com/2369428/1140334
8. Add a validator to the Data Model
· Original address: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-validation-to-the-model
· Address: http://powertoolsteam.blog.51cto.com/2369428/1147449
9. query details and delete records
· Original address: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/examining-the-details-and-delete-methods
· Address: http://powertoolsteam.blog.51cto.com/2369428/1149311
10. Third-party control Studio for ASP. NET Wijmo MVC4 tool Application
Address: http://powertoolsteam.blog.51cto.com/2369428/1196469