What is Entity Framework Core?
Entity Framework Core (EF Core) is a modern, open-source, extensible data access technology for .NET. It is a rewrite of the popular Entity Framework 6 (EF6) with a focus on performance, extensibility, and cross-platform support. EF Core allows developers to work with a data source (like a SQL database) using .NET objects, eliminating the need to write most of the data-access code themselves.
It provides a flexible programming model that supports both the Code-First and Database-First approaches, enabling you to define your domain model and let EF Core handle the mapping to the database schema.
Key Features
Cross-Platform Support
Runs on Windows, macOS, and Linux.
Performance
Significant performance improvements over EF6.
Extensibility
Highly extensible, allowing customization of many aspects.
LINQ Integration
Leverages Language Integrated Query (LINQ) for querying data.
Migrations
Manages database schema changes over time.
Provider Model
Supports various database providers (SQL Server, PostgreSQL, SQLite, MySQL, etc.).
Getting Started
Getting started with EF Core is straightforward. You'll typically need to install the necessary NuGet packages.
Install EF Core Packages
For example, to use EF Core with SQL Server:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
Define Your Model
Create your .NET classes that represent your data:
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public List<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public Blog Blog { get; set; }
}
Create a DbContext
Define a class that inherits from DbContext and represents your database session:
using Microsoft.EntityFrameworkCore;
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=Blogging;Trusted_Connection=True;");
}
}
Create Database Migrations
Use EF Core Tools to create and apply database migrations:
dotnet ef migrations add InitialCreate
dotnet ef database update