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.mdffrom 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.
Theenable-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 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.99M}, new Movie {Title = "Ghostbusters", ReleaseDate = DateTime.Parse ("1984-3-13 "), Genre =" comedy ", Price = 8.99M}, new Movie {Title =" Ghostbusters 2 ", ReleaseDate = DateTime.Parse (" 1986-2-23 "), Ge NRE = "comedy", Price = 9.99M}, new Movie {Title = "Rio Bravo", ReleaseDate = DateTime.Parse ("1959-4-15"), Genre = "West Ern ", 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-databasein 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 come to build 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 files in the previous steps movie.mdf
.
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, it may be because you have deleted the database and update-database
you have run the application before you execute it. 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
Movie
adds a new property to the existing class Rating
. Open the Models\movie.cs file and add the following Rating
properties:
public string Rating {get; set;}
The complete Movie
class is as follows:
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 application Build>build Move or Ctrl-shift-b.
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. So that the new properties can be displayed in the browser Rating
.
Open the \views\movies\index.cshtml file, and add <th>Rating</th>
the column header after the price column. Then add a <td>
column to display @item.Rating
the value. The following is an updated index.cshtml View Template:
@model ienumerable<mvcmovie.models.movie> @{viewbag.title = "Index";}
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.
<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>
You have now updated the application code to support the new Rating
properties.
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 most recent Movie
model class is different from the Movie
schema of an existing database table. (There are no columns in the database table Rating
.) )
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
add-migration
The 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, new inheritance from DbMIgration
the definition of the 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 Rating
add fields 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.
ASP. MVC4 Getting Started Guide (7): Add new fields to movie tables and models