DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Data Engineering
  3. Databases
  4. Steps to Add New Field With Code First Approach in .NET Core

Steps to Add New Field With Code First Approach in .NET Core

Learn how to use the Code first approach to add new fields to your .NET Core web application and sync this field with a database.

Neel Bhatt user avatar by
Neel Bhatt
CORE ·
Aug. 20, 18 · Tutorial
Like (2)
Save
Tweet
Share
59.25K Views

Join the DZone community and get the full member experience.

Join For Free

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:

Add-Migration EmployeeLocation 

Side Note: If you want to reverse the migration then use the below command:

Remove-Migration 

Once you run the  add-migration command, a new migration class will be created and opened, in that, you can see a new column has been added to the Employee table. This class contains the details of the newly added column.

The whole class is created automatically and it looks like below:
using Microsoft.EntityFrameworkCore.Migrations;

namespace NeelCodeFirstDemo.Migrations {
 public partial class EmployeeLocation: Migration {
  protected override void Up(MigrationBuilder migrationBuilder) {
   migrationBuilder.AddColumn < int > (
    name: "EmployeeLocation",
    table: "Employees",
    nullable: false,
    defaultValue: 0);
  }

  protected override void Down(MigrationBuilder migrationBuilder) {
   migrationBuilder.DropColumn(
    name: "EmployeeLocation",
    table: "Employees");
  }
 }
}

Once  add migration is done, the next step is to update the database with the new changes. For that write below command:

Update-Database 

Here, if you observe the logs, you can see all the queries getting fired when we run the above command. The new column, EmployeeLocation, is added with the default value 0.

You can cross check this in the database, where a new column will be added after running the above command:

Run the Application

Once the migration is over, run the application. You can see the EmployeeLocationis 0 for all the columns. Employee Location is nothing but the Country Code:

Let us modify Create.cshtml to add a new Employee with  EmployeeLocation.

Add below in Create view:
<div class="form-group">
<label asp-for="EmployeeLocation" class="control-label"></label>
<input asp-for="EmployeeLocation" class="form-control" />
<span asp-validation-for="EmployeeLocation" class="text-danger"></span>
</div>

As we are adding a new field, we need to add this new field to the Bind list of the  Creates method of the  EmployeeController, as shown below:

public async Task<IActionResult> Creates([Bind("EmployeeId,EmployeeName,EmployeeAge,EmployeeLocation,DepartmentId")] Employee employee)
{

//// Rest of the code
Once this is done, let us add a new Employee with the Employee Location set to 12:

If the new record is added successfully, it means everything is working as expected.

Hope this helps.

Database

Published at DZone with permission of Neel Bhatt, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • DevOps for Developers: Continuous Integration, GitHub Actions, and Sonar Cloud
  • Solving the Kubernetes Security Puzzle
  • mTLS Everywere
  • Stop Using Spring Profiles Per Environment

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: