🚀 Entity Framework: Code First Approach in .NET
Entity Framework (EF) is a powerful Object-Relational Mapper (ORM) that allows developers to work with databases using C# classes instead of raw SQL queries.
🔷 What is Entity Framework?
As discussed in the previous blog, Entity Framework simplifies database interaction by mapping C# objects to database tables, enabling clean, maintainable, and strongly typed data access.
+-------------------+ +---------------------+ +------------------+
| C# Classes | ----> | Entity Framework | ----> | Database |
| (Entities) | | (ORM Layer) | | (Tables/Rows) |
+-------------------+ +---------------------+ +------------------+
🔷 Entities and Domain Classes
📌 Entity Classes
Entity classes represent database tables. Each object represents a row.
Example:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
📌 Domain Classes
Domain classes represent business logic and real-world concepts.
- Entities → have identity (Primary Key)
- Value Objects → no identity
- Aggregates → group of related entities
Example structure:
Domain Layer
|
|--- Student (Entity)
|--- Address (Value Object)
|--- Course (Aggregate Root)
🔷 Entity Framework Approaches
| Approach | Description | Use Case |
|---|---|---|
| Code First | Start with C# classes | New applications |
| Database First | Start with existing database | Legacy systems |
🚀 Hands-on: Code First Approach
Step 1: Create C# Model Classes
Instead of creating a database first, we define models:
public class Student
{
public int Id { get; set; } // Primary Key
public string Name { get; set; }
public int Age { get; set; }
}
Step 2: Create DbContext
using Microsoft.EntityFrameworkCore;
public class AppDbContext : DbContext
{
public DbSet<Student> Students { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseMySql(
"server=localhost;database=newdb;user=root;password=;",
new MySqlServerVersion(new Version(8, 0, 0))
);
}
}
Step 3: Install NuGet Packages
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Tools
Pomelo.EntityFrameworkCore.MySql
Step 4: Create Migration
Add-Migration InitialCreate
Step 5: Create Database from Code
Update-Database
👉 This automatically generates:
- Database
- Tables
- Schema based on C# models
📊 Code First Workflow Diagram
C# Entity Classes
|
v
DbContext + Migrations
|
v
EF Core Model Builder
|
v
Database Creation
|
v
Tables Generated Automatically
🔧 CRUD Application Flow
User Input
|
v
Controller / Program.cs
|
v
DbContext
|
v
Entity Framework Core
|
v
Database (Insert / Update / Delete / Fetch)
💻 Sample CRUD Code (Code First)
Insert Operation
using (var context = new AppDbContext())
{
Student s = new Student
{
Name = "John",
Age = 20
};
context.Students.Add(s);
context.SaveChanges();
}
Fetch Data
using (var context = new AppDbContext())
{
var students = context.Students.ToList();
foreach (var s in students)
{
Console.WriteLine(s.Name);
}
}
Update Data
using (var context = new AppDbContext())
{
var student = context.Students.First();
student.Name = "Updated Name";
context.SaveChanges();
}
Delete Data
using (var context = new AppDbContext())
{
var student = context.Students.First();
context.Students.Remove(student);
context.SaveChanges();
}
🎯 Key Learnings
- Understand ORM and Code First workflow
- Define database using C# classes
- Learn migration-based schema management
- Perform CRUD without writing SQL
- Build scalable backend applications
📌 When to Use Code First?
✔ New applications
✔ Microservices architecture
✔ Agile development (frequent changes)
✔ Full control over schema design
✔ Domain-driven design (DDD)
📎 Code First vs Database First (Quick Insight)
| Feature | Code First | Database First |
|---|---|---|
| Starting point | C# classes | Existing DB |
| Schema control | Developer | Database |
| Flexibility | High | Limited |
| Best for | Modern apps | Legacy systems |
Comments
Post a Comment