Ad Code

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

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

Code First Approach in .NET Core MVC

Code First Approach in ASP.NET Core MVC?

Code First is complete dynamic approach of entity framework where we create database configuration and table dynamically using dB Context class.

 1)  Create Web Project using ASP.NET Core MVC Project Template


2)  Add Library from Nuget Package


EntityFrameworkCore.Design

EntityFrameworkCore.SQLServer

EntityFrameworkCore.Tools


3) Create Local Database using Server Explorer


4)  Create Model Class Like this

using System.ComponentModel.DataAnnotations;


namespace WebApplication3.Models

{

    public class Employee

    {

        [Key]

        public int Id { get; set; }

        public string Name { get; set; }    

        public string Email { get; set; }

        public string Mobileno { get; set; }

    }

}



5)  Create DbContext class


using Microsoft.EntityFrameworkCore;

namespace WebApplication3.Models
{
    public class EmployeeDBContext:DbContext
    {
        public EmployeeDBContext(DbContextOptions<EmployeeDBContext> options)
        : base(options) // The base(options) call passes the options to the base DbContext class constructor.
        {

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

    }
}


6) Create Connection String under appSettings.json

{
    "ConnectionStrings": {
        "MyDatabaseConnection": "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\Shiva-PC\\Documents\\empdb.mdf;Integrated Security=True;Connect Timeout=30"
    },
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft.AspNetCore": "Warning"
        }
    },
    "AllowedHosts": "*"
}


7)  Configure Connection String inder Program.cs

using Microsoft.EntityFrameworkCore;
using WebApplication3.Models;

            builder.Services.AddDbContext<EmployeeDBContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("MyDatabaseConnection"))
);


8) Open Nuget Package Manager Console

Add-Migration MigrationFileName


9) Update-Database

10) Create Controller with EntityFramework Scaffold Template 


Example Create Primary Key & Foreign Key:

We have 2 Tables:

  • Department (Parent Table)
  • Employee (Child Table)

Relationship:

  • One Department → Many Employees
  • Employee → Belongs to One Department

Step 1: Create Department Model (Primary Table)

public class Department
{
public int DepartmentId { get; set; } // Primary Key

public string DepartmentName { get; set; }

// Navigation Property
public ICollection<Employee> Employees { get; set; }
}

Important

EF Core automatically treats:

DepartmentId

as Primary Key by convention.

You can also explicitly define:

using System.ComponentModel.DataAnnotations;

public class Department
{
[Key]
public int DepartmentId { get; set; }

public string DepartmentName { get; set; }

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

Step 2: Create Employee Model (Foreign Key Table)

public class Employee
{
public int EmployeeId { get; set; } // Primary Key

public string Name { get; set; }

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

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

Step 3: Configure DbContext

using Microsoft.EntityFrameworkCore;

public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}

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

Fluent API is a way to configure database relationships, keys, and rules in Entity Framework Core using code inside DbContext instead of using Data Annotations (Attributes).

In simple words:

Fluent API = Configure Model using C# Code (not attributes)

Step 4: Using Fluent API (Optional but Recommended)

You can also configure Foreign Key in OnModelCreating

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Employee>()
.HasOne(e => e.Department)
.WithMany(d => d.Employees)
.HasForeignKey(e => e.DepartmentId);
}

Step 5: Add Migration

Open Package Manager Console

Add-Migration InitialCreate

Step 6: Update Database

Update-Database

Ignore AutoIncrment:

Example Full Model

public class Department
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int DepartmentId { get; set; }

public string DepartmentName { get; set; }
}

1. Normal (Synchronous) Controller

Action Method

A normal controller method executes line by line and blocks the thread until the operation

completes.

Example — Normal Controller Method

public IActionResult GetUsers()
{
var users = _context.Users.ToList();
return View(users);
}

What Happens Internally

  1. Request comes to server
  2. Thread is allocated
  3. Database call executes
  4. Thread waits (blocked) until DB returns data
  5. Response sent to user

Problem

If many users hit the server:

  • Threads become blocked
  • Server performance decreases
  • App becomes slow under heavy load

2. Asynchronous Controller Action Method

An async method allows the thread to be released while waiting for long operations like:

  • Database calls
  • API calls
  • File operations
  • Network operations

Example — Async Controller Method

public async Task<IActionResult> GetUsers()
{
var users = await _context.Users.ToListAsync();
return View(users);
}

What Happens Internally

  1. Request comes
  2. Thread allocated
  3. DB call starts
  4. Thread released back to thread pool
  5. When DB completes → thread reassigned
  6. Response returned

This makes application faster and scalable


Key Differences

FeatureNormal MethodAsync Method

Thread BlockingYesNo
PerformanceSlower under loadBetter performance
ScalabilityLowHigh
Suitable ForSmall appsLarge apps / APIs
Return TypeIActionResultTask<IActionResult>
KeywordsNoneasync, await

Return Types in Async Methods

Common async return types:

Task<IActionResult>
Task<JsonResult>
Task<ViewResult>
Task<List<User>>
Task<string>

Example:

public async Task<JsonResult> GetData()
{
var data = await _context.Users.ToListAsync();
return Json(data);
}

When Should You Use Async

Use Async When:

✅ Database operations
✅ API calls
✅ File upload/download
✅ Long-running operations
✅ External service calls

Do NOT use Async for:

❌ Simple calculations
❌ Small in-memory operations

Example (No need async)

public IActionResult Add()
{
int x = 5 + 10;
return View();
}

Important Async Keywords

async

Marks method as asynchronous

public async Task<IActionResult> Index()

await

Waits for async operation without blocking thread

await _context.Users.ToListAsync();

Real-World Example

Without Async

1000 users request → 1000 threads blocked → slow

With Async

1000 users request → threads reused → fast


Best Practice (Microsoft Recommendation)

Always use Async methods when working with:

  • Entity Framework Core
  • Web APIs
  • Microservices
  • Cloud applications

Entity Framework Async Methods

SyncAsync
ToList()ToListAsync()
FirstOrDefault()FirstOrDefaultAsync()
SaveChanges()SaveChangesAsync()
Find()FindAsync()

Example:

await _context.SaveChangesAsync();

Interview Definition

Synchronous Method
A method that blocks the thread until execution completes.

Asynchronous Method
A method that allows non-blocking execution using async and await to improve performance

and scalability.


If you'd like, I can also explain:

  • Async in Web API
  • Async vs Multithreading
  • Async lifecycle in .NET Core
  • Performance diagram

Post a Comment

0 Comments