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.
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.
Open your project's directory in the terminal or command prompt and run the following commands:
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
Other common providers:
dotnet add package Npgsql.EntityFrameworkCore.PostgreSQLdotnet add package Microsoft.EntityFrameworkCore.Sqlitedotnet add package Pomelo.EntityFrameworkCore.MySqlCreate Plain Old CLR Objects (POCOs) to represent your database tables. These classes will map directly to the columns in your tables.
// 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; }
}
// Models/Category.cs
public class Category
{
public int CategoryId { get; set; }
public string Name { get; set; }
public List Products { get; set; }
}
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.
// 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);
}
}
[Key], [Required], [Column]) directly on your model classes, or use the Fluent API in OnModelCreating for more complex configurations.
You need to register your DbContext with the .NET's dependency injection container. This is typically done in your application's startup configuration file.
// 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();
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=YourDatabaseName;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
YourDatabaseName and the server details with your actual database connection information.
Migrations allow you to evolve your database schema over time as your application models change, without losing your existing data.
dotnet ef migrations add InitialCreate
dotnet ef database update
dotnet tool install --global dotnet-ef
DotNetCliToolReference to your project file (.csproj):
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="5.0.0" />
</ItemGroup>
(Adjust version as needed)
You have successfully set up Entity Framework Core!
DbSet properties.Refer to the official Entity Framework Core documentation for comprehensive details and advanced features.