Adding a New Field to the Movie Model and Table
[!NOTE] An updated version of this tutorial is available here that uses ASP.NET MVC 5 and Visual Studio 2013. It’s more secure, much simpler to follow and demonstrates more features.
In this section you’ll use Entity Framework Code First Migrations to migrate some changes to the model classes so the change is applied to the database.
By default, when you use Entity Framework Code First to automatically create a database, as you did earlier in this tutorial, Code First adds a table to the database to help track whether the schema of the database is in sync with the model classes it was generated from. If they aren’t in sync, the Entity Framework throws an error. This makes it easier to track down issues at development time that you might otherwise only find (by obscure errors) at run time.
Setting up Code First Migrations for Model Changes
If you are using Visual Studio 2012, double click the Movies.mdf file from Solution Explorer to open the database tool. Visual Studio Express for Web will show Database Explorer, Visual Studio 2012 will show Server Explorer. If you are using Visual Studio 2010, use SQL Server Object Explorer.
In the database tool (Database Explorer, Server Explorer or SQL Server Object Explorer), right click on MovieDBContext
and select Delete to drop the movies database.
Navigate back to Solution Explorer. Right click on the Movies.mdf file and select Delete to remove the movies database.
Build the application to make sure there are no errors.
From the Tools menu, click Library Package Manager and then Package Manager Console.
In the Package Manager Console window at the PM>
prompt enter “Enable-Migrations -ContextTypeName MvcMovie.Models.MovieDBContext”.
The Enable-Migrations command (shown above) creates a Configuration.cs file in a new Migrations folder.
Visual Studio opens the Configuration.cs file. Replace the Seed
method in the Configuration.cs file with the following code:
[!code-csharpMain]
1: protected override void Seed(MvcMovie.Models.MovieDBContext context)
2: {
3: context.Movies.AddOrUpdate( i => i.Title,
4: new Movie
5: {
6: Title = "When Harry Met Sally",
7: ReleaseDate = DateTime.Parse("1989-1-11"),
8: Genre = "Romantic Comedy",
9: Price = 7.99M
10: },
11:
12: new Movie
13: {
14: Title = "Ghostbusters ",
15: ReleaseDate = DateTime.Parse("1984-3-13"),
16: Genre = "Comedy",
17: Price = 8.99M
18: },
19:
20: new Movie
21: {
22: Title = "Ghostbusters 2",
23: ReleaseDate = DateTime.Parse("1986-2-23"),
24: Genre = "Comedy",
25: Price = 9.99M
26: },
27:
28: new Movie
29: {
30: Title = "Rio Bravo",
31: ReleaseDate = DateTime.Parse("1959-4-15"),
32: Genre = "Western",
33: Price = 3.99M
34: }
35: );
36:
37: }
Right click on the red squiggly line under Movie
and select Resolve then using MvcMovie.Models;
Doing so adds the following using statement:
[!code-csharpMain]
1: using MvcMovie.Models;
[!NOTE]
Code First Migrations calls the
Seed
method after every migration (that is, calling update-database in the Package Manager Console), and this method updates rows that have already been inserted, or inserts them if they don’t exist yet.
Press CTRL-SHIFT-B to build the project.(The following steps will fail if your don’t build at this point.)
The next step is to create a DbMigration
class for the initial migration. This migration to creates a new database, that’s why you deleted the movie.mdf file in a previous step.
In the Package Manager Console window, enter the command “add-migration Initial” to create the initial migration. The name “Initial” is arbitrary and is used to name the migration file created.
Code First Migrations creates another class file in the Migrations folder (with the name {DateStamp}_Initial.cs ), and this class contains code that creates the database schema. The migration filename is pre-fixed with a timestamp to help with ordering. Examine the {DateStamp}_Initial.cs file, it contains the instructions to create the Movies table for the Movie DB. When you update the database in the instructions below, this {DateStamp}_Initial.cs file will run and create the the DB schema. Then the Seed method will run to populate the DB with test data.
In the Package Manager Console, enter the command “update-database” to create the database and run the Seed method.
If you get an error that indicates a table already exists and can’t be created, it is probably because you ran the application after you deleted the database and before you executed update-database
. In that case, delete the Movies.mdf file again and retry the update-database
command. If you still get an error, delete the migrations folder and contents then start with the instructions at the top of this page (that is delete the Movies.mdf file then proceed to Enable-Migrations).
Run the application and navigate to the /Movies URL. The seed data is displayed.
Adding a Rating Property to the Movie Model
Start by adding a new Rating
property to the existing Movie
class. Open the Models.cs file and add the Rating
property like this one:
[!code-csharpMain]
1: public string Rating { get; set; }
The complete Movie
class now looks like the following code:
[!code-csharpMain]
1: public class Movie
2: {
3: public int ID { get; set; }
4: public string Title { get; set; }
5: public DateTime ReleaseDate { get; set; }
6: public string Genre { get; set; }
7: public decimal Price { get; set; }
8: public string Rating { get; set; }
9: }
Build the application using the Build >Build Movie menu command or by pressing CTRL-SHIFT-B.
Now that you’ve updated the Model
class, you also need to update the .cshtml and .cshtml view templates in order to display the new Rating
property in the browser view.
Open the.cshtml file and add a <th>Rating</th>
column heading just after the Price column. Then add a <td>
column near the end of the template to render the @item.Rating
value. Below is what the updated Index.cshtml view template looks like:
[!code-cshtmlMain]
1: @model IEnumerable<MvcMovie.Models.Movie>
2:
3: @{
4: ViewBag.Title = "Index";
5: }
6:
7: <h2>Index</h2>
8:
9: <p>
10: @Html.ActionLink("Create New", "Create")
11: </p>
12: <table>
13: <tr>
14: <th>
15: @Html.DisplayNameFor(model => model.Title)
16: </th>
17: <th>
18: @Html.DisplayNameFor(model => model.ReleaseDate)
19: </th>
20: <th>
21: @Html.DisplayNameFor(model => model.Genre)
22: </th>
23: <th>
24: @Html.DisplayNameFor(model => model.Price)
25: </th>
26: <th>
27: @Html.DisplayNameFor(model => model.Rating)
28: </th>
29: <th></th>
30: </tr>
31:
32: @foreach (var item in Model) {
33: <tr>
34: <td>
35: @Html.DisplayFor(modelItem => item.Title)
36: </td>
37: <td>
38: @Html.DisplayFor(modelItem => item.ReleaseDate)
39: </td>
40: <td>
41: @Html.DisplayFor(modelItem => item.Genre)
42: </td>
43: <td>
44: @Html.DisplayFor(modelItem => item.Price)
45: </td>
46: <td>
47: @Html.DisplayFor(modelItem => item.Rating)
48: </td>
49: <td>
50: @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
51: @Html.ActionLink("Details", "Details", new { id=item.ID }) |
52: @Html.ActionLink("Delete", "Delete", new { id=item.ID })
53: </td>
54: </tr>
55: }
56:
57: </table>
Next, open the .cshtml file and add the following markup near the end of the form. This renders a text box so that you can specify a rating when a new movie is created.
[!code-cshtmlMain]
1: <div class="editor-label">
2: @Html.LabelFor(model => model.Rating)
3: </div>
4: <div class="editor-field">
5: @Html.EditorFor(model => model.Rating)
6: @Html.ValidationMessageFor(model => model.Rating)
7: </div>
You’ve now updated the application code to support the new Rating
property.
Now run the application and navigate to the /Movies URL. When you do this, though, you’ll see one of the following errors:
You’re seeing this error because the updated Movie
model class in the application is now different than the schema of the Movie
table of the existing database. (There’s no Rating
column in the database table.)
There are a few approaches to resolving the error:
- Have the Entity Framework automatically drop and re-create the database based on the new model class schema. This approach is very convenient when doing active development on a test database; it allows you to quickly evolve the model and database schema together. The downside, though, is that you lose existing data in the database — so you don’t want to use this approach on a production database! Using an initializer to automatically seed a database with test data is often a productive way to develope an application. For more information on Entity Framework database initializers, see Tom Dykstra’s ASP.NET MVC/Entity Framework tutorial.
- Explicitly modify the schema of the existing database so that it matches the model classes. The advantage of this approach is that you keep your data. You can make this change either manually or by creating a database change script.
- Use Code First Migrations to update the database schema.
For this tutorial, we’ll use Code First Migrations.
Update the Seed method so that it provides a value for the new column. Open Migrations.cs file and add a Rating field to each Movie object.
[!code-csharpMain]
1: new Movie
2: {
3: Title = "When Harry Met Sally",
4: ReleaseDate = DateTime.Parse("1989-1-11"),
5: Genre = "Romantic Comedy",
6: Rating = "G",
7: Price = 7.99M
8: },
Build the 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 examine the current movie model with the current movie DB schema and create the necessary code to migrate the DB to the new model. The AddRatingMig is arbitrary and is used to name the migration file. It’s helpful to use a meaningful name for the migration step.
When this command finishes, Visual Studio opens the class file that defines the new DbMIgration
derived class, and in the Up
method you can see the code that creates the new column.
[!code-csharpMain]
1: public partial class AddRatingMig : DbMigration
2: {
3: public override void Up()
4: {
5: AddColumn("dbo.Movies", "Rating", c => c.String());
6: }
7:
8: public override void Down()
9: {
10: DropColumn("dbo.Movies", "Rating");
11: }
12: }
Build the solution, and then enter the “update-database” command in the Package Manager Console window.
The following image shows the output in the Package Manager Console window (The date stamp prepending AddRatingMig will be different.)
Re-run the application and navigate to the /Movies URL. You can see the new Rating field.
Click the Create New link to add a new movie. Note that you can add a rating.
Click Create. The new movie, including the rating, now shows up in the movies listing:
You should also add the Rating
field to the Edit, Details and SearchIndex view templates.
You could enter the “update-database” command in the Package Manager Console window again and no changes would be made, because the schema matches the model.
In this section you saw how you can modify model objects and keep the database in sync with the changes. You also learned a way to populate a newly created database with sample data so you can try out scenarios. Next, let’s look at how you can add richer validation logic to the model classes and enable some business rules to be enforced.
|