In this section, you will use the entity Framework Code first to implement operations on the model classes. This allows these operations and changes to be applied to the database.
By default, as you did in the previous tutorial, using the Entity Framework code first to automatically create a database, code first is a table added to the database that 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 handy for discovering errors at development time, or you may find this problem at run time. (The problem was discovered by an obscure error message.) )
Set Code first migrations for changes to the object model
If you are using Visual Studio 2012, double-click Movies.mdf from Solution Explorer to open the database Tools. Visual Studio Express for Web will display Database Explorer, and Visual Studio 2012 will display the server Resource Manager. If you are using Visual Studio 2010, use SQL server Object Explorer.
In the 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 the application to ensure that there are no compilation errors.
From the Tools menu, click Library Package Manager, and then click Package Manager Console.
In the Package Manager console window, enter "Enable-migrations–contexttypename MvcMovie.Models.MovieDBContext" at the pm> prompt.
The enable-migrations command creates a Configuration.cs file in the Migrations folder, as shown above.
Open the Configuration.cs file in Visual Studio. Replace the seed method in the Configuration.cs file with the following code:
protected Override voidSeed (MvcMovie.Models.MovieDBContext context) {context. Movies.addorupdate (i = I.title,NewMovie {Title ="When Harry Met Sally", ReleaseDate = DateTime.Parse ("1989-1-11"), Genre ="Romantic Comedy", Price =7.99M},NewMovie {Title ="Ghostbusters", ReleaseDate = DateTime.Parse ("1984-3-13"), Genre ="Comedy", Price =8.99M},NewMovie {Title ="Ghostbusters 2", ReleaseDate = DateTime.Parse ("1986-2-23"), Genre ="Comedy", Price =9.99M},NewMovie {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 then click Using Mvcmovie.models;
When you do this, the following using statements are added:
Using Mvcmovie.models;
Each code first migrations calls the seed method (that is, calls Update-database in the Package Manager console), and the call updates the row: Updates the row that has already been inserted, or inserts a nonexistent row.
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 that initializes the database migration. This migration class will create a new database, which is why you want to delete 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 arbitrary and is the name used to create the migrated file.
Code first migrations will create another class file in the Migrations folder (with the file name: {Datestamp}_initial.cs), which will create a schema for the database. The migration file name uses timestamps as a prefix to help with sorting and finding. 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 schema of the DB is created. The seed method will then run to populate the test data for the DB.
In the Package Manager console, enter the command "Update-database" to create the database and run the seed method.
If you receive an error that the table already exists and cannot be created, you may have deleted the database, and you ran the application before you executed 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 to a movie model
Adds a new rating property to the existing movie class. Open the Models\movie.cs file and add the following rating property:
public string Rating {get; set;}
The complete movie class is as follows:
Public classMovie { Public intID {Get;Set; } Public stringTitle {Get;Set; } PublicDateTime ReleaseDate {Get;Set; } Public stringGenre {Get;Set; } Public decimalPrice {Get;Set; } Public stringRating {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 you can display the new rating properties in the browser.
Open the \views\movies\index.cshtml file and add the <th>Rating</th> column header 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";}<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 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.
<class= "Editor-label"></div> < class= "Editor-field"></div>
You have now updated the application code to support the new rating property.
Now run the application, and then browse to the/movies URL. However, when you do this, you will see one of the following error messages:
You now see this error because in the application, the latest movie model class and the schema of the existing Database movie table are different. (There is no rating column 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 file name parameter that is used to name the migration file. It will help to make the migration step a meaningful name.
When the command is complete, open the class file with visual Studio, inherit the definition from 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 prefix timestamp for addratingmig will be different).
Rerun the application, and then browse to 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 a movie.
Click Create. New movies, including ratings, will be displayed in the movie list:
You should also 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, there will be no new changes, because the database schema and model classes 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 examples of using 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 mandatory business rule validation on the model class.
Full document Download: ASP. MVC4 Getting Started Guide. pdf
--------------------------------------------------------------------------------------------------------------- -----
Translator Note:
This series of 9 articles, translated from the official ASP. NET MVC4 tutorial, because this series of articles concise, space moderate, from an example to explain, the full text finally completed a small system to manage the film, very suitable for the novice MVC4 ASP, and start the development work. 9 Articles for:
1. Introduction to ASP. 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. Accessing 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. Validating editing methods and editing views
· 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 a new field 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://www.cnblogs.com/powertoolsteam/archive/2013/02/26/2933105.html
8. Adding 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://www.cnblogs.com/powertoolsteam/archive/2013/03/05/2944030.html
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://www.cnblogs.com/powertoolsteam/archive/2013/03/07/2948000.html
10. Third-party control Studio for ASP. Wijmo MVC4 Tools App
· Address: http://www.cnblogs.com/powertoolsteam/archive/2013/05/09/3068699.html
ASP. MVC4 Getting Started Guide (7): Add new fields to movie tables and models