Entity Framework Core (Intro)

Advanced 25 min read Lesson 5 of 5

Entity Framework Core (EF Core) is an ORM (Object-Relational Mapper) — it lets you work with the database using C# classes and LINQ instead of writing raw SQL by hand.

Install the packages

Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.Tools

Define your model

public class Student
{
    public int StudentId { get; set; }
    public string FirstName { get; set; } = string.Empty;
    public string LastName { get; set; } = string.Empty;
    public string Email { get; set; } = string.Empty;
    public DateTime EnrolledOn { get; set; }
}

Define your DbContext

using Microsoft.EntityFrameworkCore;

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

    public DbSet<Student> Students => Set<Student>();
}

Register it in Program.cs

builder.Services.AddDbContext<SchoolDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("SchoolDb")));

Using it — no raw SQL required

// Read
var students = await context.Students
    .Where(s => s.LastName == "Ahmed")
    .OrderBy(s => s.FirstName)
    .ToListAsync();

// Insert
context.Students.Add(new Student { FirstName = "Nour", LastName = "Saeed", Email = "nour@example.com" });
await context.SaveChangesAsync();

// Update
var student = await context.Students.FindAsync(1);
student!.Email = "updated@example.com";
await context.SaveChangesAsync();

// Delete
var toDelete = await context.Students.FindAsync(3);
context.Students.Remove(toDelete!);
await context.SaveChangesAsync();

ADO.NET vs EF Core — when to use which

ADO.NET gives you full control and top performance for complex queries. EF Core is faster to write, safer by default, and is what most modern ASP.NET Core apps use. Learning both, as you just did, makes you far more versatile than developers who only know one.

Key Takeaway

EF Core is an ORM that lets you work with databases using C# classes and LINQ. It's faster to write and safer by default.

Test Your Knowledge - Take Quiz