.NET Entity Framework Core

Setting Up Entity Framework Core

This guide will walk you through the essential steps to set up Entity Framework Core (EF Core) in your .NET project. EF Core is a modern, cross-platform, open-source version of Microsoft's popular Object-Relational Mapper (ORM) for .NET.

1

Install EF Core Packages

You'll need to install the appropriate EF Core NuGet packages for your database provider. The most common providers are:

You'll also typically need the tools package for migrations:

You can install these using the .NET CLI:

dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools

Replace Microsoft.EntityFrameworkCore.SqlServer with your desired database provider package.

2

Define Your DbContext

The DbContext is the main class that represents a session with the database and allows you to query and save data. It should inherit from Microsoft.EntityFrameworkCore.DbContext.

Create a new C# class (e.g., MyDbContext.cs) and define your context:

using Microsoft.EntityFrameworkCore;

namespace YourProject.Data
{
    public class MyDbContext : DbContext
    {
        // Constructor that takes DbContextOptions
        public MyDbContext(DbContextOptions<MyDbContext> options)
            : base(options)
        {
        }

        // DbSet properties for your entities
        public DbSet<Product> Products { get; set; }
        public DbSet<Category> Categories { get; set; }

        // Optional: Override OnConfiguring for basic configuration (less common in modern apps)
        // protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        // {
        //     if (!optionsBuilder.IsConfigured)
        //     {
        //         // Example for SQL Server
        //         optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;");
        //     }
        // }

        // Optional: Override OnModelCreating for advanced configuration
        // protected override void OnModelCreating(ModelBuilder modelBuilder)
        // {
        //     // Configure entities here if needed
        //     modelBuilder.Entity<Product>().HasKey(p => p.ProductId);
        // }
    }

    // Example entity classes (define these in separate files or within the same file)
    public class Product
    {
        public int ProductId { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public int CategoryId { get; set; }
        public Category Category { get; set; }
    }

    public class Category
    {
        public int CategoryId { get; set; }
        public string Name { get; set; }
        public ICollection<Product> Products { get; set; }
    }
}
3

Configure Dependency Injection

In modern .NET applications (like ASP.NET Core), you'll typically configure your DbContext using dependency injection in your Startup.cs or Program.cs file.

For ASP.NET Core applications (Program.cs in .NET 6+):

using Microsoft.EntityFrameworkCore;
using YourProject.Data; // Assuming your DbContext is in this namespace

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

// Configure DbContext
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<MyDbContext>(options =>
    options.UseSqlServer(connectionString)); // Or UseSqlite, UseNpgsql, etc.

var app = builder.Build();

// ... rest of your Program.cs ...

For older ASP.NET Core applications (Startup.cs):

using Microsoft.EntityFrameworkCore;
using YourProject.Data; // Assuming your DbContext is in this namespace

public void ConfigureServices(IServiceCollection services)
{
    // ... other services ...

    var connectionString = Configuration.GetConnectionString("DefaultConnection");
    services.AddDbContext<MyDbContext>(options =>
        options.UseSqlServer(connectionString)); // Or UseSqlite, UseNpgsql, etc.

    services.AddControllersWithViews();
}

Ensure you have a connection string named DefaultConnection in your appsettings.json:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

Adjust the connection string and provider (UseSqlServer) to match your setup.

4

Create Migrations

Migrations allow you to evolve your database schema over time as your model changes. You create migration files that contain code to update your database.

Open your terminal or command prompt in your project directory and run:

dotnet ef migrations add InitialCreate

This will generate a new migration file in an Migrations folder. You can then apply this migration to your database:

dotnet ef database update

For ASP.NET Core applications, you can also use the Package Manager Console:

Add-Migration InitialCreate
Update-Database

Next Steps