Skip to main content

Entity Framework: Code First Approach in .NET

 

🚀 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

ApproachDescriptionUse Case
Code FirstStart with C# classesNew applications
Database FirstStart with existing databaseLegacy 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)

FeatureCode FirstDatabase First
Starting pointC# classesExisting DB
Schema controlDeveloperDatabase
FlexibilityHighLimited
Best forModern appsLegacy systems

Comments

Popular posts from this blog

Entity Framework: Database First Approach in .NET

Getting Started with Entity Framework: Database First Approach in .NET Entity Framework (EF) is a powerful Object-Relational Mapper (ORM) that allows developers to work with databases using C# objects instead of writing raw SQL queries. 🔷 What is Entity Framework? Entity Framework simplifies database interaction by mapping database tables to C# classes, enabling clean and maintainable code. +-------------------+ +---------------------+ +------------------+ | C# Classes | ----> | Entity Framework | ----> | Database | | (Entities) | | (ORM Layer) | | (Tables/Rows) | +-------------------+ +---------------------+ +------------------+ 🔷 Entities and Domain Classes 📌 Entity Classes Entity classes represent database tables. Each object corresponds to a row in the table. 📌 Domain Classes Domain classes represent business logic and real-world entities. Entities: Have primary keys Val...

C# Keywords

C# Keywords Many different reserved words or keywords are used in C# programming. They are categorised as described below. It is advised to properly get familiar with the categories, functionality, and usage of each of them before we move forward. If, somewhere, you feel you are not able to grasp the correct meaning, make a note of it and in the future specific examples where it is explicitly used, you would be able to recall and revise it. Some examples for certain keywords can be viewed at: Link 1. Data Types and Modifiers bool Explanation: Represents a Boolean value that can be either true or false . It is an alias for the system type System.Boolean . Example: bool isCoding = true; byte Explanation: Represents an 8-bit unsigned integer that can store values from 0 to 255. Example: byte age = 25; char Explanation: Represents a single 16-bit Unicode character. It is enclosed in single quotes. Example: char grade = 'A'; class Explanation: Used to declare a reference t...