⚙️

Entity Framework Core Setup Guide

Introduction

Welcome to the setup guide for Entity Framework Core (EF Core) in your .NET projects. EF Core is a powerful, lightweight, and extensible Object-Relational Mapper (ORM) that enables .NET developers to work with databases using .NET objects.

This guide will walk you through the essential steps to get EF Core up and running, covering installation, creating a DbContext, and defining your models.

Step 1: Install Entity Framework Core Packages

The first step is to add the necessary EF Core NuGet packages to your project. The core package is Microsoft.EntityFrameworkCore, and you'll also need a provider package for your specific database.

Using the .NET CLI

Open your project's directory in the terminal or command prompt and run the following commands:

Install the core package:

dotnet add package Microsoft.EntityFrameworkCore

Install a database provider (example for SQL Server):

dotnet add package Microsoft.EntityFrameworkCore.SqlServer

Other common providers:

Note: Ensure you are targeting a compatible .NET version for your EF Core and provider packages.

Step 2: Define Your Model Classes

Create Plain Old CLR Objects (POCOs) to represent your database tables. These classes will map directly to the columns in your tables.

Example Model: Product

// Models/Product.cs public class Product { public int ProductId { get; set; } // Primary Key public string Name { get; set; } public decimal Price { get; set; } public string Description { get; set; } }

Example Model: Category

// Models/Category.cs public class Category { public int CategoryId { get; set; } public string Name { get; set; } public List Products { get; set; } }

Step 3: Create Your DbContext

The DbContext class is the primary way to interact with your database. It represents a session with the database and allows you to query and save data. It also allows you to configure your model.

Example DbContext: ApplicationDbContext

// Data/ApplicationDbContext.cs using Microsoft.EntityFrameworkCore; using YourAppName.Models; // Assuming your models are in a 'Models' folder public class ApplicationDbContext : DbContext { public ApplicationDbContext(DbContextOptions options) : base(options) { } public DbSet Products { get; set; } public DbSet Categories { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { // Configure relationships and constraints here if needed modelBuilder.Entity() .HasMany(c => c.Products) .WithOne(); // Assuming Product doesn't have a direct CategoryId property but uses navigation // Example of fluent API for configuration modelBuilder.Entity() .Property(p => p.Price) .HasColumnType("decimal(18,2)"); // Specify precision and scale base.OnModelCreating(modelBuilder); } }
Tip: You can use Data Annotations (like [Key], [Required], [Column]) directly on your model classes, or use the Fluent API in OnModelCreating for more complex configurations.

Step 4: Configure Your DbContext in Startup/Program.cs

You need to register your DbContext with the .NET's dependency injection container. This is typically done in your application's startup configuration file.

Example Configuration (ASP.NET Core with `Program.cs` - .NET 6+)

// Program.cs using Microsoft.EntityFrameworkCore; using YourAppName.Data; // Assuming DbContext is in 'Data' folder var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllersWithViews(); // Configure the DbContext var connectionString = builder.Configuration.GetConnectionString("DefaultConnection"); builder.Services.AddDbContext(options => options.UseSqlServer(connectionString)); // Or .UseNpgsql(), .UseSqlite(), etc. var app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run();

Example `appsettings.json` (for connection string)

{ "ConnectionStrings": { "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=YourDatabaseName;Trusted_Connection=True;MultipleActiveResultSets=true" }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*" }
Important: Replace YourDatabaseName and the server details with your actual database connection information.

Step 5: Create Database Migrations

Migrations allow you to evolve your database schema over time as your application models change, without losing your existing data.

Create an initial migration:

dotnet ef migrations add InitialCreate

Apply the migration to your database:

dotnet ef database update
Prerequisite: You need to install the EF Core tools globally or locally.
Global: dotnet tool install --global dotnet-ef
Local: Add a DotNetCliToolReference to your project file (.csproj):
<ItemGroup>
  <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="5.0.0" />
</ItemGroup>
(Adjust version as needed)

Next Steps

You have successfully set up Entity Framework Core!

Refer to the official Entity Framework Core documentation for comprehensive details and advanced features.