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.
Return to solution Resource Manager. Right-click the movies. MDF file and selectDeleteTo delete the Movie Database.
Build ApplicationProgramTo make sure there are no compilation errors.
SlaveToolsClickLibrary Package ManagerAnd then clickPackage Manager Console.
InSoftware Package Manager ConsoleWindow
PM> enter "enable-migrations-contexttypename mvcmovie. Models. moviedbcontext" at the prompt ".
(As shown above)Enable-migrationsCommand will create 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 followingCode:
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 });}
Right-click the red wave line that appears under movie and selectResolveThen clickUsing Mvcmovie. Models;
After doing so, the following using statement will be added:
Using mvcmovie. models;
Each code first migrations calls the seed method (that is, it is called in the Package Manager ConsoleUpdate-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.
Code first migrations creates another class file in the migrations folder (the file name is:{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.
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:
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:
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 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:
@ 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> <TH> </Th> </tr> @ foreach (VAR item in Model) {<tr> <TD> @ HTML. displayfor (modelitem => item. title) </TD> <TD> @ HTML. displayfor (modelitem => item. releasedate) </TD> <TD> @ HTML. displayfor (modelitem => item. genre) </TD> <TD> @ HTML. displayfor (modelitem => item. price) </TD> <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\ 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.
<Div class = "editor-label"> @ HTML. labelfor (model => model. rating) </div> <Div class = "editor-field"> @ HTML. editorfor (model => model. rating) @ HTML. validationmessagefor (model => model. rating) </div>
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:
You can see this error because in the application, the latestMovie
Model class and existing databaseMovie
The table schema is different. (In the 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.99 m
},
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:
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 thenPackage Manager ConsoleEnter the "Update-Database" command in the window.
The image below showsPackage Manager ConsoleWindow output (the prefix timestamp of addratingmig will be different ).
Run the application again and then browse the/movies URL. You can see the new rating field.
ClickCreatenewLink to add a new movie. Note: you can add a rating for a movie.
ClickCreate. New movies, including ratings, will be displayed in the movie list:
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..
Download the complete document:ASP. NET mvc41_1_timeout
Bytes --------------------------------------------------------------------------------------------------------------------
Note:
9 articles in this seriesArticle, 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 article address:Http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/intro-to-aspnet-mvc-4
· Translation address:Http://www.cnblogs.com/powertoolsteam/archive/2012/11/01/2749906.html
2. Add a controller
· Original article address:Http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-controller
· Translation address:Http://www.cnblogs.com/powertoolsteam/archive/2012/11/02/2751015.html
3. Add a view
· Original article address:Http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-view
· Translation address:Http://www.cnblogs.com/powertoolsteam/archive/2012/11/06/2756711.html
4. Add a model
· Original article address:Http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-model
· Translation address:Http://www.cnblogs.com/powertoolsteam/archive/2012/12/17/2821495.html
5. Access the data model from the Controller
· Original article address:Http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/accessing-your-models-data-from-a-controller
· Translation address:Http://www.cnblogs.com/powertoolsteam/archive/2013/01/11/2855935.html
6. Verify the editing method and view
· Original article address:Http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/examining-the-edit-methods-and-edit-view
· Translation address:Http://www.cnblogs.com/powertoolsteam/archive/2013/01/24/2874622.html
7. Add new fields to the movie table and Model
· Original article address:Http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-new-field-to-the-movie-model-and-table
· Translation address:Http://www.cnblogs.com/powertoolsteam/archive/2013/02/26/2933105.html
8. Add a validator to the Data Model
· Original article address:Http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-validation-to-the-model
· Address: http://www.cnblogs.com/powertoolsteam/archive/2013/03/05/2944030.html
9. query details and delete records
· Original article 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/powertoolsteam/archive/2013/03/07/2948000.html
10. Third-party control studio for ASP. NET wijmo mvc4 tool Application
Address: http://www.cnblogs.com/powertoolsteam/archive/2013/05/09/3068699.html