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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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
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

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Comparing Managed Postgres Options on The Azure Marketplace
  • Useful System Table Queries in Relational Databases
  • Introducing Graph Concepts in Java With Eclipse JNoSQL
  • Manual Sharding in PostgreSQL: A Step-by-Step Implementation Guide

Trending

  • Supervised Fine-Tuning (SFT) on VLMs: From Pre-trained Checkpoints To Tuned Models
  • The Role of AI in Identity and Access Management for Organizations
  • Advancing Robot Vision and Control
  • Next Evolution in Integration: Architecting With Intent Using Model Context Protocol
  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.

By 
Neel Bhatt user avatar
Neel Bhatt
·
Aug. 20, 18 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
69.8K 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.

Related

  • Comparing Managed Postgres Options on The Azure Marketplace
  • Useful System Table Queries in Relational Databases
  • Introducing Graph Concepts in Java With Eclipse JNoSQL
  • Manual Sharding in PostgreSQL: A Step-by-Step Implementation Guide

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!