Steps to Add New Field With Code First Approach in .NET Core
source link: https://www.tuicool.com/articles/hit/zqyUniU
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
I have written a post on Code first approach with . Net Core which you can find here .
In the above post, I have not covered adding an additional new field in the model and migrating it to the database using the Code first approach.
Let us look at that scenario in this post.
For this, we will use the code which we implemented during the Code first approach demo , you can find the code here .
Add a New Field
Let us first add a new field to the Employee model. We will add EmployeeLocation
as shown below:
Note:Please note that EmployeeLocation
is nothing but the Country Code, I have not added any additional table for the current post.
public class Employee { public int EmployeeId { get; set; } public string EmployeeName { get; set; } public int EmployeeAge { get; set; } public int EmployeeLocation { get; set; } //// New field public int DepartmentId { get; set; } public Department Department { get; set; } }
Once this is done, let us add this new field to the Index.cshtml view so that we can see new column in the browser:
For this, add below for header:<th> @Html.DisplayNameFor(model => model.EmployeeLocation) </th>And add the below code for the table values:
<td> @Html.DisplayFor(modelItem => item.EmployeeLocation) </td>
We have added the fields in the model, but we have not informed our database of this change yet.
For this reason, if you run the application, you will see the below exception:Run Two Commands, That's It
For this, we just need to run two commands in the Package Management Console (PMC)
The first command is:Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK