Вы находитесь на странице: 1из 8

Adding a New Field to the Movie Model and Table : Official Microsoft...

1 de 8

http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-m...

Sign In | Join

Search ASP.NET

Home

Get Started

Overview

Downloads

Videos

Web Pages

Samples

Web Forms

MVC

Forum

Solutions

Books

Community

Open Source

Home / MVC / Tutorials / Chapter 8. ASP.NET MVC 4 Beta / Getting Started with ASP.NET MVC 4 / Adding a New
Field to the Movie Model and Table

Try MVC
controls that
will truly save
you time!

Adding a New Field to the Movie Model and Table


By Rick Anderson | February 15, 2012

Forums

www.telerik.com/ajax

In this section you'll make some changes to the model classes and learn how you can update the database schema to
match the model changes.

Adding a Rating Property to the Movie Model

THIS IS A MULTI-PART ARTICLE


Now viewing article 7 of 9
Intro to ASP.NET MVC 4

Start by adding a new Rating property to the existing Movie class. Open the Movie.cs file and add the Rating
property like this one:

Adding a Controller
publicstringRating{get;set;}
Adding a View
The complete Movie class now looks like the following code:
Adding a Model
publicclassMovie
{
publicintID{get;set;}
publicstringTitle{get;set;}
publicDateTimeReleaseDate{get;set;}
publicstringGenre{get;set;}
publicdecimalPrice{get;set;}
publicstringRating{get;set;}
}

Accessing Your Model's Data


from a Controller
Examining the Edit Methods
and Edit View
Adding a New Field to the
Movie Model and Table

Recompile the application using the Debug > Build Movie menu command.
Now that you've updated the Model class, you also need to update the \Views\Movies\Index.cshtml and \Views\Movies
\Create.cshtml view templates in order to support the new Rating property.
Open the \Views\Movies\Index.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:

Adding Validation to the


Model
Examining the Details and
Delete Methods

@modelIEnumerable<MvcMovie.Models.Movie>
@{
ViewBag.Title="Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("CreateNew","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>
Powered by

and Umbraco

Privacy Statement | Terms of Service | Site Feedback | Advertise With Us

Follow Us On:
Twitter | Facebook

Feedback on ASP.NET | File Bugs

20/04/2012 19:42

Adding a New Field to the Movie Model and Table : Official Microsoft...

2 de 8

http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-m...

</th>
<th>
@Html.DisplayNameFor(model=>model.Rating)
</th>
<th></th>
</tr>
@foreach(variteminModel){
<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 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.
<divclass="editorlabel">
@Html.LabelFor(model=>model.Rating)
</div>
<divclass="editorfield">
@Html.EditorFor(model=>model.Rating)
@Html.ValidationMessageFor(model=>model.Rating)
</div>

Managing Model and Database Schema Differences


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 the following error:

20/04/2012 19:42

Adding a New Field to the Movie Model and Table : Official Microsoft...

3 de 8

http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-m...

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.)
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. The
sync-checking feature is what causes the error message to be displayed that you just saw.
There are two approaches to resolving the error:
1. 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!
2. 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.
For this tutorial, we'll use the first approach you'll have the Entity Framework Code First automatically re-create the
database anytime the model changes.

Automatically Re-Creating the Database on Model Changes


Let's update the application so that Code First automatically drops and re-creates the database anytime you change
the model for the application.

Warning You should enable this approach of automatically dropping and re-creating the
database only when you're using a development or test database, and never on a production
database that contains real data. Using it on a production server can lead to data loss.

In Solution Explorer, right click the Models folder, select Add, and then select Class.

20/04/2012 19:42

Adding a New Field to the Movie Model and Table : Official Microsoft...

4 de 8

http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-m...

Name the class "MovieInitializer". Update the MovieInitializer class to contain the following code:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Data.Entity;
namespaceMvcMovie.Models{
publicclassMovieInitializer:DropCreateDatabaseIfModelChanges<MovieDBContext>{
protectedoverridevoidSeed(MovieDBContextcontext){
varmovies=newList<Movie>{

newMovie{Title="WhenHarryMetSally",
ReleaseDate=DateTime.Parse("1989111"),
Genre="RomanticComedy",
Rating="R",
Price=7.99M},
newMovie{Title="Ghostbusters",
ReleaseDate=DateTime.Parse("1984313"),
Genre="Comedy",
Rating="R",
Price=8.99M},

newMovie{Title="Ghostbusters2",
ReleaseDate=DateTime.Parse("1986223"),
Genre="Comedy",
Rating="R",
Price=9.99M},
newMovie{Title="RioBravo",
ReleaseDate=DateTime.Parse("1959415"),
Genre="Western",
Rating="R",
Price=3.99M},
};
movies.ForEach(d=>context.Movies.Add(d));
}
}
}

The MovieInitializer class specifies that the database used by the model should be dropped and automatically
re-created if the model classes ever change. DropCreateDatabaseIfModelChanges initializer specifies the DB should
be re-created only if the schema changes. Alternatively, you could use the DropCreateDatabaseAlways initializer to
always recreate and re-seed the database with data the first time that a context is used in the application domain. The
DropCreateDatabaseAlways approach is useful in some integration testing scenarios. The code includes a Seed
method to specify some default data to automatically add to the database any time it's created (or re-created). This
provides a useful way to populate the database with some test data, without requiring you to manually populate it
each time you make a model change.
Now that you've defined the MovieInitializer class, you'll want to wire it up so that each time the application runs,
it checks whether the model classes are different from the schema in the database. If they are, you can run the
initializer to re-create the database to match the model and then populate the database with the sample data.

20/04/2012 19:42

Adding a New Field to the Movie Model and Table : Official Microsoft...

5 de 8

http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-m...

Open the Global.asax file that's at the root of the MvcMovies project:

The Global.asax file contains the class that defines the entire application for the project, and contains an
Application_Start event handler that runs when the application first starts.
In the Application_Start method and add a call to Database.SetInitializer at the beginning of the method,
as shown below:
protectedvoidApplication_Start(){
Database.SetInitializer<MovieDBContext>(newMovieInitializer());
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
BundleTable.Bundles.RegisterTemplateBundles();
}

Put the cursor on Database, right click and select Resolve, thenusingSystem.Data.Entity;

20/04/2012 19:42

Adding a New Field to the Movie Model and Table : Official Microsoft...

6 de 8

http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-m...

Do the same for MovieDBContext to add a using statement for MvcMovie.Models. Alternatively, add two using
statements to the top of the file. The first references the Entity Framework namespace, and the second references the
namespace where our MovieInitializer class lives:
usingSystem.Data.Entity;//Database.SetInitialize
usingMvcMovie.Models;//MovieInitializer

The Database.SetInitializer statement you just added indicates that the database used by the MovieDBContext
instance should be automatically deleted and re-created if the schema and the database don't match. And as you
saw, it will also populate the database with the sample data that's specified in the MovieInitializer class.
Close the Global.asax file.
Re-run the application and navigate to the /Movies URL. When the application starts, it detects that the model
structure no longer matches the database schema. It automatically re-creates the database to match the new model
structure and populates the database with the sample movies:

Click the Create New link to add a new movie. Note that you can add a rating.

20/04/2012 19:42

Adding a New Field to the Movie Model and Table : Official Microsoft...

7 de 8

http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-m...

Click Create. The new movie, including the rating, now shows up in the movies listing:

20/04/2012 19:42

Adding a New Field to the Movie Model and Table : Official Microsoft...

8 de 8

http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-m...

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.

By Rick Anderson, Rick Anderson works as a programmer writer for Microsoft, focusing
on ASP.NET MVC, jQuery and Entity Framework. He enjoys working with the top
contributors in the ASP.NET MVC forum.

Previous

You're Viewing

Examining the Edit Methods and Edit


View

Adding a New Field to the Movie


Model and Table

Comments (1)

You must be logged in to leave a comment.

Next
Adding Validation to the Model

Show Comments

20/04/2012 19:42

Вам также может понравиться