Ad Code

✨🎆 JOIN MERN, JAVA, PYTHON, AI, DEVOPS, SALESFORCE Courses 🎆✨

Get 100% Placement Oriented Program CLICK to new more info click

Entity Framework Core – Primary Key, Foreign Key & Navigation Properties (Code First Approach)

 

Entity Framework Core – Primary Key, Foreign Key & Navigation Properties (Code First Approach)

In this tutorial, we will create a complete Department and Employee relationship using Entity Framework Core Code First Approach in ASP.NET Core Web API with SQL Server.

We will cover:

  1. Primary Key (PK)

  2. Foreign Key (FK)

  3. Navigation Properties

  4. One-to-Many Relationship

  5. Data Annotations

  6. Fluent API

  7. DbContext configuration

  8. Database migrations

  9. CRUD operations

  10. How EF Core manages relationships internally

1. Understand the relationship

Consider a company with multiple departments:

  • IT Department

  • HR Department

  • Sales Department

  • Finance Department

Each department can have multiple employees, but each employee belongs to one department.

One-to-Many Relationship

Department

DepartmentId (Primary Key)

DepartmentName

1 : Many

Employee 1

DepartmentId (FK)

Employee 2

DepartmentId (FK)

Employee 3

DepartmentId (FK)

Database relationship:

Department Table

Employee Table

DepartmentId (PK)

EmployeeId (PK)

DepartmentName

EmployeeName

Salary

DepartmentId (FK)

The DepartmentId column in Employee references the DepartmentId column in Department.

2. Create Department Entity

Create a folder named Entities and add Department.cs.


namespace EFCoreDemo.Entities
{
    public class Department
    {
        // Primary Key
        public int DepartmentId { get; set; }

        public string DepartmentName { get; set; }

        // Navigation Property
        public ICollection<Employee> Employees { get; set; }
            = new List<Employee>();
    }
}

Explanation:

  • DepartmentId: Primary Key. EF Core recognizes it by convention.

  • DepartmentName: Stores the department name.

  • Employees: Collection navigation property. It represents multiple employees belonging to one department.

Important: ICollection<Employee> is not a database column. It helps EF Core navigate between related entities.

3. Create Employee Entity

Add Employee.cs in the same folder.


namespace EFCoreDemo.Entities
{
    public class Employee
    {
        // Primary Key
        public int EmployeeId { get; set; }

        public string EmployeeName { get; set; }

        public decimal Salary { get; set; }

        // Foreign Key
        public int DepartmentId { get; set; }

        // Navigation Property
        public Department Department { get; set; }
    }
}

Explanation:

  • EmployeeId: Primary Key.

  • DepartmentId: Foreign Key.

  • Department: Reference navigation property. It represents the department to which the employee belongs.

Notice the difference:

Property

Purpose

DepartmentId

Actual Foreign Key column

Department

Navigation Property

Employees

Collection Navigation Property

4. Understand Navigation Properties

There are two types of navigation properties in our example.

A. Collection Navigation Property

Inside Department:

public ICollection<Employee> Employees { get; set; }
    = new List<Employee>();

It means one department can have multiple employees.

Example:

var department = new Department
{
    DepartmentName = "IT",
    Employees = new List<Employee>
    {
        new Employee
        {
            EmployeeName = "Rahul",
            Salary = 50000
        },
        new Employee
        {
            EmployeeName = "Amit",
            Salary = 60000
        }
    }
};

B. Reference Navigation Property

Inside Employee:

public Department Department { get; set; }

It means an employee can navigate to its associated department.

For example:

Console.WriteLine(employee.Department.DepartmentName);

This accesses the department name through the employee object.

Remember this concept:

  • Collection navigation property: One department → Many employees.

  • Reference navigation property: One employee → One department.

5. Understand Primary Key and Foreign Key using Data Annotations

EF Core automatically identifies primary keys using naming conventions.

For example:

public int DepartmentId { get; set; }

EF Core recognizes this as a Primary Key.

However, you can explicitly define keys using Data Annotations.

Department.cs


using System.ComponentModel.DataAnnotations;

namespace EFCoreDemo.Entities
{
    public class Department
    {
        [Key]
        public int DepartmentId { get; set; }

        [Required]
        [MaxLength(100)]
        public string DepartmentName { get; set; }

        public ICollection<Employee> Employees { get; set; }
            = new List<Employee>();
    }
}

Employee.cs


using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace EFCoreDemo.Entities
{
    public class Employee
    {
        [Key]
        public int EmployeeId { get; set; }

        [Required]
        [MaxLength(100)]
        public string EmployeeName { get; set; }

        public decimal Salary { get; set; }

        [ForeignKey("Department")]
        public int DepartmentId { get; set; }

        public Department Department { get; set; }
    }
}

Important attributes:

Attribute

Purpose

[Key]

Defines Primary Key

[ForeignKey]

Defines Foreign Key relationship

[Required]

Makes a property mandatory

[MaxLength(100)]

Defines maximum length

Note: [ForeignKey("Department")] is optional here because EF Core can automatically identify DepartmentId as the foreign key for the Department navigation property.

6. Configure Relationship using Fluent API

Another way to configure relationships is Fluent API.

This is especially useful when you want to manage relationships centrally inside DbContext.

Create ApplicationDbContext.cs.


using Microsoft.EntityFrameworkCore;
using EFCoreDemo.Entities;

namespace EFCoreDemo.Data
{
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(
            DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }

        public DbSet<Department> Departments { get; set; }

        public DbSet<Employee> Employees { get; set; }

        protected override void OnModelCreating(
            ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            // Department Primary Key
            modelBuilder.Entity<Department>()
                .HasKey(d => d.DepartmentId);

            // Employee Primary Key
            modelBuilder.Entity<Employee>()
                .HasKey(e => e.EmployeeId);

            // One-to-Many Relationship
            modelBuilder.Entity<Department>()
                .HasMany(d => d.Employees)
                .WithOne(e => e.Department)
                .HasForeignKey(e => e.DepartmentId)
                .OnDelete(DeleteBehavior.Restrict);
        }
    }
}

Understand Fluent API step by step

The most important code is:

modelBuilder.Entity<Department>()
    .HasMany(d => d.Employees)
    .WithOne(e => e.Department)
    .HasForeignKey(e => e.DepartmentId);

Let's understand each method:

Method

Meaning

Entity<Department>()

Configure Department entity

HasMany()

One department has many employees

WithOne()

Each employee has one department

HasForeignKey()

Employee.DepartmentId is the FK

Why DeleteBehavior.Restrict?

It prevents deleting a department while employees are still associated with it. You must first reassign or delete those employees.

7. Data Annotations vs Fluent API

Data Annotations

Fluent API

Defined inside entity class

Defined inside DbContext

Uses attributes

Uses method chaining

Simple configurations

Advanced configurations

[Key]

HasKey()

[ForeignKey]

HasForeignKey()

[MaxLength]

HasMaxLength()

For classroom teaching, explain both approaches. In a real project, Fluent API is often preferred for centralized and complex relationship configuration.

8. Configure SQL Server Connection

Open appsettings.json.

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=CompanyDB;Trusted_Connection=True;TrustServerCertificate=True"
  }
}

Now open Program.cs.


using EFCoreDemo.Data;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

builder.Services.AddDbContext<ApplicationDbContext>(
    options =>
        options.UseSqlServer(
            builder.Configuration.GetConnectionString(
                "DefaultConnection"
            )
        )
);

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

app.UseSwagger();
app.UseSwaggerUI();

app.UseHttpsRedirection();

app.MapControllers();

app.Run();

Install the required NuGet packages:

Install-Package Microsoft.EntityFrameworkCore.SqlServer

Install-Package Microsoft.EntityFrameworkCore.Tools

Install-Package Microsoft.EntityFrameworkCore.Design

Make sure the EF Core package versions are compatible with your .NET and EF Core versions.

9. Create Database using Code First Migrations

Now we will generate database tables from our C# entity classes.

Open Package Manager Console.

Step 1: Create Migration

Add-Migration InitialCreate

What happens?

EF Core compares your entity model with its previous migration snapshot and generates migration code to create the tables and relationship.

Step 2: Update Database

Update-Database

Now SQL Server creates the database and tables.

CompanyDB

Created

Departments

DepartmentId (PK)

DepartmentName

Employees

EmployeeId (PK)

EmployeeName

Salary

DepartmentId (FK → Departments.DepartmentId)

What SQL relationship is generated?

Conceptually, EF Core creates a foreign key similar to:

ALTER TABLE Employees
ADD CONSTRAINT FK_Employees_Departments_DepartmentId
FOREIGN KEY (DepartmentId)
REFERENCES Departments(DepartmentId);

Notice that DepartmentId exists in the Employees table, not as an extra column in the Departments table.

10. Insert Department and Employees

Now let's understand how navigation properties help us insert related records.

Scenario 1: Insert Department with Multiple Employees

using (var context = new ApplicationDbContext(options))
{
    var department = new Department
    {
        DepartmentName = "IT",

        Employees = new List<Employee>
        {
            new Employee
            {
                EmployeeName = "Rahul",
                Salary = 50000
            },

            new Employee
            {
                EmployeeName = "Amit",
                Salary = 60000
            },

            new Employee
            {
                EmployeeName = "Priya",
                Salary = 55000
            }
        }
    };

    context.Departments.Add(department);

    context.SaveChanges();
}

What happens internally?

  1. EF Core inserts the IT department.

  2. SQL Server generates its DepartmentId.

  3. EF Core assigns that DepartmentId to all three employees.

  4. EF Core inserts all three employees with the correct foreign key.

You do not need to manually assign DepartmentId when you create employees through the Employees navigation property.

Scenario 2: Insert Employee into an Existing Department

Suppose IT Department already exists with DepartmentId = 1.

var employee = new Employee
{
    EmployeeName = "Vijay",
    Salary = 45000,
    DepartmentId = 1
};

context.Employees.Add(employee);

context.SaveChanges();

Here, we only assign the foreign key.

We don't need to load the complete Department object.

Scenario 3: Insert Employee using Navigation Property

var employee = new Employee
{
    EmployeeName = "Sanjay",
    Salary = 65000,

    Department = new Department
    {
        DepartmentId = 1
    }
};

context.Employees.Add(employee);

context.SaveChanges();

This also works, but for an existing department, using DepartmentId = 1 is generally simpler.

11. Retrieve Data using Navigation Properties (Include)

This is one of the most important concepts in Entity Framework Core.

Suppose you want to retrieve all departments along with their employees.

Without Include()

var departments = context.Departments.ToList();

This retrieves department records only.

It does not automatically load all related employees.

With Include()

using Microsoft.EntityFrameworkCore;

var departments = context.Departments
    .Include(d => d.Employees)
    .ToList();

Now EF Core retrieves departments along with their employees.

Understand Include():

.Include(d => d.Employees)
  • d represents a Department object.

  • Employees is the collection navigation property.

  • Include() tells EF Core to load related employees.

Example: Retrieve Employees with Department

var employees = context.Employees
    .Include(e => e.Department)
    .ToList();

Now each employee has its associated Department loaded.

You can access:

foreach (var employee in employees)
{
    Console.WriteLine(employee.EmployeeName);

    Console.WriteLine(
        employee.Department.DepartmentName
    );
}

SQL equivalent

Conceptually, EF Core generates a JOIN query:

SELECT
    e.EmployeeId,
    e.EmployeeName,
    e.Salary,
    e.DepartmentId,
    d.DepartmentName
FROM Employees e
INNER JOIN Departments d
    ON e.DepartmentId = d.DepartmentId;

Important
Include() is called Eager Loading. It loads related data as part of the query.

12. Complete CRUD API Example

Let's create an ASP.NET Core Web API controller.

Create DepartmentsController.cs.


using EFCoreDemo.Data;
using EFCoreDemo.Entities;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace EFCoreDemo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class DepartmentsController : ControllerBase
    {
        private readonly ApplicationDbContext _context;

        public DepartmentsController(ApplicationDbContext context)
        {
            _context = context;
        }

        // GET: api/departments
        [HttpGet]
        public async Task<IActionResult> GetDepartments()
        {
            var departments = await _context.Departments
                .Include(d => d.Employees)
                .Select(d => new
                {
                    d.DepartmentId,
                    d.DepartmentName,

                    Employees = d.Employees.Select(e => new
                    {
                        e.EmployeeId,
                        e.EmployeeName,
                        e.Salary,
                        e.DepartmentId
                    })
                })
                .ToListAsync();

            return Ok(departments);
        }

        // GET: api/departments/1
        [HttpGet("{id}")]
        public async Task<IActionResult> GetDepartment(int id)
        {
            var department = await _context.Departments
                .Include(d => d.Employees)
                .Where(d => d.DepartmentId == id)
                .Select(d => new
                {
                    d.DepartmentId,
                    d.DepartmentName,
                    Employees = d.Employees.Select(e => new
                    {
                        e.EmployeeId,
                        e.EmployeeName,
                        e.Salary
                    })
                })
                .FirstOrDefaultAsync();

            if (department == null)
                return NotFound();

            return Ok(department);
        }

        // POST: api/departments
        [HttpPost]
        public async Task<IActionResult> CreateDepartment(
            Department department)
        {
            _context.Departments.Add(department);

            await _context.SaveChangesAsync();

            return Ok(department);
        }

        // PUT: api/departments/1
        [HttpPut("{id}")]
        public async Task<IActionResult> UpdateDepartment(
            int id,
            Department department)
        {
            if (id != department.DepartmentId)
                return BadRequest();

            var existingDepartment = await _context.Departments
                .FindAsync(id);

            if (existingDepartment == null)
                return NotFound();

            existingDepartment.DepartmentName =
                department.DepartmentName;

            await _context.SaveChangesAsync();

            return Ok(existingDepartment);
        }

        // DELETE: api/departments/1
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteDepartment(int id)
        {
            var department = await _context.Departments
                .FindAsync(id);

            if (department == null)
                return NotFound();

            _context.Departments.Remove(department);

            await _context.SaveChangesAsync();

            return Ok("Department deleted successfully");
        }
    }
}

Note: The delete operation will fail if employees are still associated with the department because we configured DeleteBehavior.Restrict.

Also, for production applications, use request DTOs and validate input rather than accepting EF entities directly.

13. Employee Controller

Create EmployeesController.cs.


using EFCoreDemo.Data;
using EFCoreDemo.Entities;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace EFCoreDemo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmployeesController : ControllerBase
    {
        private readonly ApplicationDbContext _context;

        public EmployeesController(ApplicationDbContext context)
        {
            _context = context;
        }

        // GET: api/employees
        [HttpGet]
        public async Task<IActionResult> GetEmployees()
        {
            var employees = await _context.Employees
                .Include(e => e.Department)
                .Select(e => new
                {
                    e.EmployeeId,
                    e.EmployeeName,
                    e.Salary,

                    DepartmentName =
                        e.Department.DepartmentName
                })
                .ToListAsync();

            return Ok(employees);
        }

        // POST: api/employees
        [HttpPost]
        public async Task<IActionResult> CreateEmployee(
            Employee employee)
        {
            var departmentExists = await _context.Departments
                .AnyAsync(d =>
                    d.DepartmentId == employee.DepartmentId);

            if (!departmentExists)
                return BadRequest("Invalid DepartmentId");

            _context.Employees.Add(employee);

            await _context.SaveChangesAsync();

            return Ok(employee);
        }

        // GET: api/employees/1
        [HttpGet("{id}")]
        public async Task<IActionResult> GetEmployee(int id)
        {
            var employee = await _context.Employees
                .Include(e => e.Department)
                .Where(e => e.EmployeeId == id)
                .Select(e => new
                {
                    e.EmployeeId,
                    e.EmployeeName,
                    e.Salary,
                    DepartmentName =
                        e.Department.DepartmentName
                })
                .FirstOrDefaultAsync();

            if (employee == null)
                return NotFound();

            return Ok(employee);
        }

        // DELETE: api/employees/1
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteEmployee(int id)
        {
            var employee = await _context.Employees.FindAsync(id);

            if (employee == null)
                return NotFound();

            _context.Employees.Remove(employee);

            await _context.SaveChangesAsync();

            return Ok("Employee deleted successfully");
        }
    }
}

14. Test APIs using Swagger

After running your application, test the following endpoints.

HTTP Method

API

Purpose

GET

/api/departments

Get all departments with employees

GET

/api/departments/1

Get one department with employees

POST

/api/departments

Create department

PUT

/api/departments/1

Update department

DELETE

/api/departments/1

Delete department

GET

/api/employees

Get employees with department

POST

/api/employees

Create employee

GET

/api/employees/1

Get employee with department

DELETE

/api/employees/1

Delete employee

POST: Create Department

Request:

{
  "departmentName": "IT",
  "employees": [
    {
      "employeeName": "Rahul",
      "salary": 50000
    },
    {
      "employeeName": "Amit",
      "salary": 60000
    }
  ]
}

POST: Create Employee

Request:

{
  "employeeName": "Vijay",
  "salary": 45000,
  "departmentId": 1
}

GET: Department with Employees

Expected response:

[
  {
    "departmentId": 1,
    "departmentName": "IT",
    "employees": [
      {
        "employeeId": 1,
        "employeeName": "Rahul",
        "salary": 50000,
        "departmentId": 1
      },
      {
        "employeeId": 2,
        "employeeName": "Amit",
        "salary": 60000,
        "departmentId": 1
      }
    ]
  }
]

15. What happens if we don't use Include()?

Consider this code:

var employees = context.Employees.ToList();

foreach (var employee in employees)
{
    Console.WriteLine(employee.Department.DepartmentName);
}

Will it automatically retrieve Department?

Not necessarily.

EF Core does not automatically load related entities by default.

There are three important loading techniques:

Technique

Meaning

Eager Loading

Use Include() to load related records

Lazy Loading

Related records load when navigation property is accessed (requires configuration)

Explicit Loading

Manually load related records using Load()

Example of Explicit Loading:

var employee = context.Employees
    .FirstOrDefault(e => e.EmployeeId == 1);

if (employee != null)
{
    context.Entry(employee)
        .Reference(e => e.Department)
        .Load();
}

For a collection navigation property:

var department = context.Departments
    .FirstOrDefault(d => d.DepartmentId == 1);

if (department != null)
{
    context.Entry(department)
        .Collection(d => d.Employees)
        .Load();
}

16. What if an Employee does not belong to any Department?

This is another important interview concept.

Required Relationship

public int DepartmentId { get; set; }

public Department Department { get; set; }

Here, DepartmentId is a non-nullable integer, so an employee must have a department.

Optional Relationship

public int? DepartmentId { get; set; }

public Department? Department { get; set; }

Here, an employee can exist without a department.

The database allows NULL in the foreign key column.

Required

Optional

int DepartmentId

int? DepartmentId

Department mandatory

Department optional

FK cannot be NULL

FK can be NULL

17. Complete Project Structure

Your project should look like this:

EFCoreDemo
│
├── Controllers
│   ├── DepartmentsController.cs
│   └── EmployeesController.cs
│
├── Data
│   └── ApplicationDbContext.cs
│
├── Entities
│   ├── Department.cs
│   └── Employee.cs
│
├── Migrations
│
├── appsettings.json
│
└── Program.cs

For a production-ready application, I recommend adding DTOs, service classes, repositories where appropriate, and proper validation. DTOs also help prevent circular JSON references between Department and Employee.

Post a Comment

0 Comments