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; }
}
}
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-DatabaseIgnore 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
- Request comes to server
- Thread is allocated
- Database call executes
- Thread waits (blocked) until DB returns data
- 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
- Request comes
- Thread allocated
- DB call starts
- Thread released back to thread pool
- When DB completes → thread reassigned
- Response returned
This makes application faster and scalable
Key Differences
Feature Normal Method Async Method Thread Blocking Yes No Performance Slower under load Better performance Scalability Low High Suitable For Small apps Large apps / APIs Return Type IActionResult Task<IActionResult> Keywords None async, 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 callsDo NOT use Async for:
❌ Simple calculations
❌ Small in-memory operationsExample (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
Sync Async 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 performanceand scalability.
If you'd like, I can also explain:
- Async in Web API
- Async vs Multithreading
- Async lifecycle in .NET Core
- Performance diagram
0 Comments
POST Answer of Questions and ASK to Doubt