Introduction to Entity Framework Core
Entity Framework Core (EF Core) is a modern object-database mapper for .NET. It allows you to work with a database using C# objects instead of writing SQL queries manually.
What is Entity Framework Core?
EF Core is an open-source, lightweight, and extensible ORM (Object-Relational Mapper) from Microsoft. It supports LINQ queries, change tracking, updates, schema migrations, and more.
EF Core works with various databases:
- SQL Server
- SQLite
- PostgreSQL
- MySQL
- In-memory (for testing)
Installing EF Core
Use NuGet to install the required packages. Example for SQL Server:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
Code-First Development
You define your data models using classes, and EF Core generates the database schema.
Define a model:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
}
Create a DbContext:
using Microsoft.EntityFrameworkCore;
public class AppDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlServer("your-connection-string");
}
Creating the Database
Use the EF Core CLI tools:
dotnet ef migrations add InitialCreate
dotnet ef database update
This will create the database schema based on your model.
Why Use EF Core?
- Reduces boilerplate SQL code
- Provides strongly-typed access to data
- Supports cross-platform development
- Easy to maintain and test
EF Core simplifies database development in .NET. Next, we’ll dive into the heart of EF Core — the DbContext
and DbSet
— to see how they manage your data.