Entity Framework Core Setup
This guide will walk you through the process of setting up Entity Framework Core (EF Core) in your .NET project. EF Core is a modern, open-source, cross-platform Object-Relational Mapper (ORM) for .NET. It allows you to work with a database using .NET objects that essentially map to your database tables.
On This Page
Introduction
EF Core simplifies data access by providing a higher-level abstraction over raw SQL queries. This guide focuses on the initial setup and basic configuration.
Prerequisites
- .NET SDK (version 6.0 or later recommended)
- A code editor (e.g., Visual Studio, VS Code)
- Basic understanding of C# and .NET development
Installation
The first step is to add the necessary EF Core NuGet packages to your project. You can do this via the NuGet Package Manager in your IDE or by using the .NET CLI.
Using the .NET CLI:
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.Design
# If using SQL Server:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
# If using SQLite:
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
# If using PostgreSQL:
dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL
Using Visual Studio NuGet Package Manager:
Right-click on your project in Solution Explorer, select "Manage NuGet Packages...", go to the "Browse" tab, search for the packages listed above, and install them.
Microsoft.EntityFrameworkCore.InMemory
) or SQLite is often convenient. For production, you'll typically use SQL Server, PostgreSQL, MySQL, etc.
Project Setup
Ensure your project is configured for .NET Core or .NET 5+. If you're creating a new project, you can use:
dotnet new webapi -n MyEfCoreApp
cd MyEfCoreApp
Creating a DbContext
The DbContext
is the primary class that represents a session with the database and allows you to query and save data. Create a class that inherits from DbContext
.
using Microsoft.EntityFrameworkCore;
namespace MyEfCoreApp.Data
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
// DbSet properties will go here for your entities
}
}
Defining Models
Create Plain Old CLR Objects (POCOs) to represent your database entities. EF Core will map these classes to tables in your database.
namespace MyEfCoreApp.Models
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
}
Now, add a DbSet<TEntity>
property to your DbContext
class for each model:
using Microsoft.EntityFrameworkCore;
using MyEfCoreApp.Models;
namespace MyEfCoreApp.Data
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Product> Products { get; set; }
}
}
Migrations
Migrations are EF Core's way of managing schema changes. They allow you to evolve your database schema over time as your application models change.
First, ensure you have the Microsoft.EntityFrameworkCore.Design
package installed. Then, you can add a migration using the .NET CLI:
# From your project directory
dotnet ef migrations add InitialCreate
This command will generate a new folder (Migrations
) containing two files: a timestamped migration file and a MyEfCoreApp.Data.ApplicationDbContextModelSnapshot.cs
file.
To apply the migration to your database, run:
dotnet ef database update
dotnet ef
commands require you to be in the project directory where your DbContext
and project file are located. You might need to install the EF Core tools globally or locally:
# Global installation (recommended)
dotnet tool install --global dotnet-ef
# Or local installation within a project
dotnet new tool-manifest
dotnet tool install dotnet-ef
Connecting to a Database
You need to configure your DbContext
to use a specific database provider and connection string. This is typically done in your application's startup code (e.g., Program.cs
in .NET 6+ or Startup.cs
in older versions).
Example for ASP.NET Core with SQL Server:
// Program.cs (.NET 6+)
using Microsoft.EntityFrameworkCore;
using MyEfCoreApp.Data;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString)); // Or UseSqlite, UseNpgsql, etc.
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
And in your appsettings.json
:
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MyEfCoreDatabase;Trusted_Connection=True;"
},
"Logging": {
// ...
},
"AllowedHosts": "*"
}
Next Steps
With EF Core set up, you can now start interacting with your database:
- Querying Data: Learn how to fetch data using LINQ.
- Saving Data: Understand how to add, update, and delete records.
- Relationships: Configure one-to-one, one-to-many, and many-to-many relationships.
- Advanced Configuration: Explore aspects like lazy loading, eager loading, and performance optimizations.
Continue to the Entity Framework Core Advanced documentation for more in-depth topics.