Introduction to Entity Framework

Easier database access with EF Core

Posted by Rodrigo Castro on December 22, 2024

Entity Framework Core (EF Core) is a modern ORM for C#. It lets you use C# classes to interact with your database: no raw SQL needed for most tasks!

🚀 Why Use EF Core?

  • Write less data access code
  • Focus on your C# models
  • Migrations for schema changes

🏗️ Basic Example

  1. Install NuGet:
    1
    
    dotnet add package Microsoft.EntityFrameworkCore.SqlServer
    
  2. Define a Model:
1
2
3
4
5
public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
}
  1. Create a DbContext:
1
2
3
4
5
6
7
8
using Microsoft.EntityFrameworkCore;

public class AppDbContext : DbContext
{
    public DbSet<User> Users { get; set; }
    protected override void OnConfiguring(DbContextOptionsBuilder options)
        => options.UseSqlServer("Server=localhost;Database=TestDb;User Id=sa;Password=YourPassword;");
}
  1. Use the Context:
1
2
3
4
5
6
7
8
using (var db = new AppDbContext())
{
    db.Users.Add(new User { Name = "Alice" });
    db.SaveChanges();

    foreach (var user in db.Users)
        Console.WriteLine(user.Name);
}

⚡ Tip

  • Use commands like dotnet ef migrations add InitialCreate for schema management.

Next: Building RESTful APIs with C#!