012. Adding a New Field, 012. addingfield
Adding a New Field
Add a new field
Author of 3-minute reading duration
By Rick Anderson
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.
In this section, we will use EF Code First to add a new field and change it 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.
When you use EF Code First to automatically create a database, Code First will add a table to the database, which will automatically track changes in the database structure and synchronize structural changes.
If they aren't in sync, EF throws an exception. This makes it easier to find inconsistent database/code issues.
If they are not synchronized, EF will throw an exception. This makes it easy to keep the Code consistent with the database.
Adding a Rating Property to the Movie Model
Add a level field to the Movie Model
OpenModels/Movie. csFile and add a Rating property:
OpenModels/Movie. csFile, and add the Rating attribute field:
1 public class Movie 2 3 {4 5 public int ID {get; set;} 6 7 public string Title {get; set ;} 8 9 10 11 [Display (Name = "Release Date")] 12 13 [DataType (DataType. date)] 14 15 public DateTime ReleaseDate {get; set;} 16 17 public string Genre {get; set;} 18 19 public decimal Price {get; set ;} 20 21 public string Rating {get; set;} 22 23}C # code
Build the app (Ctrl + Shift + B ).
Compile the application.
Because you 've added a new field to the Movie class, you also need to update the binding white list so this new property will be added.
Because you have added a field to the Movie class, you need to update the binding so that the new field can be included.
InMoviesController. cs, Update the [Bind] attribute for both the Create and Edit action methods to include the Rating property:
InMoviesController. csIn the file, update the [Bind] of the Create and Edit methods to include the Rating attribute field:
1 [Bind ("ID, Title, ReleaseDate, Genre, Price, Rating")]C # Code
You also need to update the view templates in order to display, create and edit the new Rating property in the browser view.
You also need to update the view template to display it in the browser, create and edit the Rating field.
Edit/Views/Movies/Index. cshtmlFile and add a Rating field:
Edit/Views/Movies/Index. cshtmlFile and add the Rating field:
1 <table class = "table"> 2 3 <thead> 4 5 <tr> 6 7 <th> 8 9 @ Html. displayNameFor (model => model. movies [0]. title) 10 11 </th> 12 13 <th> 14 15 @ Html. displayNameFor (model => model. movies [0]. releaseDate) 16 17 </th> 18 19 <th> 20 21 @ Html. displayNameFor (model => model. movies [0]. genre) 22 23 </th> 24 25 <th> 26 27 @ Html. displayNameFor (model => model. movies [0]. price) 28 29 </th> 30 31 <th> 32 33 @ Html. displayNameFor (model => model. movies [0]. rating) 34 35 </th> 36 37 <th> </th> 38 39 </tr> 40 41 </thead> 42 43 <tbody> 44 45 @ foreach (var item in model. movies) 46 47 {48 49 <tr> 50 51 <td> 52 53 @ Html. displayFor (modelItem => item. title) 54 55 </td> 56 57 <td> 58 59 @ Html. displayFor (modelItem => item. releaseDate) 60 61 </td> 62 63 <td> 64 65 @ Html. displayFor (modelItem => item. genre) 66 67 </td> 68 69 <td> 70 71 @ Html. displayFor (modelItem => item. price) 72 73 </td> 74 75 <td> 76 77 @ Html. displayFor (modelItem => item. rating) 78 79 </td> 80 81 <td>HTML Code
Update/Views/Movies/Create. cshtmlWith a Rating field.
Update/Views/Movies/Create. cshtmlFile to add the Rating field.
You can copy/paste the previous "form group" and let intelliisense help you update the fields.
You can copy and paste the "form group" on the front and send a smart prompt to help you update fields.
Intelliisense works with Tag Helpers.
Smart prompts use Tag Helpers to complete the work.
Note: In the RTM verison of Visual Studio 2017 you need to install the Razor Language Services for Razor intelliisense.
Note: It is now version 15.3.1. This sentence is not translated ~
This will be fixed in the next release.
This sentence is not translated ~
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 SqlException:
If the program does not run correctly when the new field is included in the database, it throws a SqlException exception:
SqlException: Invalid column name 'rating '.TXT Code
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 .)
You will see an error because the updated model is different from the structure of the DB table.
There are a few approaches to resolving the error:
The following are some solutions to the problem:
1. Have the Entity Framework automatically drop and re-create the database based on the new model class schema.
Let EF automatically delete and recreate the DB structure based on the model class structure.
This approach is very convenient early in the development cycle when you are doing active development on a test database;
In the early development cycle, this is a very convenient practice when you develop on a test library;
It allows you to quickly evolve the model and database schema together.
It allows you to quickly iterate and evolve the model and db structure.
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!
The disadvantage of doing so is that all data in the existing database will be lost. We do not want to use this method in production!
Using an initializer to automatically seed a database with test data is often a productive way to develop an application.
Using the initialization tool to automatically plant some DB data is a commonly used method for productivity improvement.
2. Explicitly modify the schema of the existing database so that it matches the model classes.
Explicitly update the structure of an existing database to match the model class in the code.
The advantage of this approach is that you keep your data.
The advantage of this approach is that you can maintain the existing data in the database.
You can make this change either manually or by creating a database change script.
You can manually or use scripts to automatically change the database.
3. Use Code First Migrations to update the database schema.
Use Code First migration to update the database structure.
For this tutorial, we'll use Code First Migrations.
In this tutorial, we will use the Code First migration method.
Update the SeedData class so that it provides a value for the new column.
Update the SeedData class to provide a value for the new field.
A sample change is shown below, but you'll want to make this change for each new Movie.
The following is an example of a change. You need to add a change for every new Movie.
1 new Movie 2 3 {4 5 Title = "When Harry Met Sally", 6 7 ReleaseDate = DateTime. parse ("1989-1-11"), 8 9 Genre = "Romantic Comedy", 10 11 Rating = "R", 12 13 Price = 7.99M14 15 },C # Code
Build the solution.
Compile the solution.
FromToolsMenu, selectNuGet Package Manager> Package Manager Console.
InToolsMenu, selectNuGet Package Manager> Package Manager ConsoleSub menu:
In the PMC, enter the following commands:
In PMC, type the following command:
1 Add-Migration Rating2 3 Update-DatabaseBash Code
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 Add-Migration Command tells the Migration framework to check the current Movie class, compare it with the DB structure, and create an appropriate code to update the database so that it matches the new model class.
The name "Rating" is arbitrary and is used to name the migration file.
"Rating" is an arbitrary name used to name the migration file name.
It's helpful to use a meaningful name for the migration file.
It is very helpful to use meaningful naming to migrate files.
If you delete all the records in the DB, the initialize will seed the DB and include the Rating field.
If you delete the data records in the DB, the initialization class will replant the DB and contain the Rating field.
You can do this with the delete links in the browser or from SSOX.
You can delete the link in the browser or on the SSOX Manager interface.
Run the app and verify you can create/edit/display movies with a Rating field.
Run the program and check the Rating fields that you can add, delete, and modify for movie.
You shoshould also add the Rating field to the Edit, Details, and Delete view templates.
You should also add the Rating field to the Edit, Details, and Delete view templates.
Mon
Tuesday