Adding a New Field?179 of 185 people found this helpful In this section you’ll use Entity Framework Code First Migrations to add a new field to the model and migrate that change to the database. When you use EF Code First to automatically create a database, 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, EF throws an exception. This makes it easier to track down issues at development time that you might otherwise only find (by obscure errors) at run time. Adding a Rating Property to the Movie Model?Open the Models/Movie.cs file and add a public class Movie{ public int ID { get; set; } public string Title { get; set; } [Display(Name = 'Release Date')] [DataType(DataType.Date)] public DateTime ReleaseDate { get; set; } public string Genre { get; set; } public decimal Price { get; set; } public string Rating { get; set; }} Build the app (Ctrl+Shift+B). Because you’ve added a new field to the [Bind('ID,Title,ReleaseDate,Genre,Price,Rating')] You also need to update the view templates in order to display, create and edit the new Edit the /Views/Movies/Index.cshtml file and add a table class='table'> tr> th> @Html.DisplayNameFor(model => model.movies[0].Genre) th> th> @Html.DisplayNameFor(model => model.movies[0].Price) th> th> @Html.DisplayNameFor(model => model.movies[0].ReleaseDate) th> th> @Html.DisplayNameFor(model => model.movies[0].Title) th> th> @Html.DisplayNameFor(model => model.movies[0].Rating) th> th>th> tr> tbody> @foreach (var item in Model.movies) { tr> td> @Html.DisplayFor(modelItem => item.Genre) td> td> @Html.DisplayFor(modelItem => item.Price) td> td> @Html.DisplayFor(modelItem => item.ReleaseDate) td> td> @Html.DisplayFor(modelItem => item.Title) td> td> @Html.DisplayFor(modelItem => item.Rating) td> Update the /Views/Movies/Create.cshtml with a The app won’t work until we update the DB to include the new field. If you run it now, you’ll get the following You’re seeing this error because the updated Movie model class is 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:
For this tutorial, we’ll use Code First Migrations. Update the new Movie { Title = 'When Harry Met Sally', ReleaseDate = DateTime.Parse('1989-1-11'), Genre = 'Romantic Comedy', Rating = 'R', Price = 7.99M }, Build the solution then open a command prompt. Enter the following commands: dotnet ef migrations add Ratingdotnet ef database update The If you delete all the records in the DB, the initialize will seed the DB and include the Run the app and verify you can create/edit/display movies with a |
|