Getting Started with Entity Framework Core: A Developer's Guide
An introduction to Entity Framework Core (EF Core), the standard ORM for .NET. Learn how to set up a DbContext, define entities, and use LINQ to query a database without writing raw SQL.
If you're a .NET developer who needs to work with a database, Entity Framework Core (EF Core) is the tool you need to know. EF Core is a modern, cross-platform, object-relational mapper (ORM) that allows you to interact with a database using C# objects instead of writing raw SQL.
This simplifies data access, reduces boilerplate code, and helps you build applications faster.
What is an ORM?
An ORM, or Object-Relational Mapper, is a library that automatically maps data from a relational database (which stores data in tables) to the objects in your application. Instead of writing SELECT * FROM Users
, you can just write _context.Users.ToList()
, and the ORM will translate your C# code into SQL for you.
Core EF Core Concepts
There are two main concepts you'll work with in EF Core:
The
DbContext
: This is the heart of EF Core. ADbContext
instance represents a session with the database. It's the class you'll use to query and save data. It contains aDbSet<T>
for each table in your database.Entities: These are the C# classes that represent the tables in your database. An instance of an entity class corresponds to a row in a table.
Getting Started: A Simple Console App
Let's build a simple application to manage a list of blogs.
1. Install EF Core Packages
You'll need a few NuGet packages. We'll use the in-memory database provider for this simple example, but you could use providers for SQL Server, PostgreSQL, SQLite, etc.
dotnet add package Microsoft.EntityFrameworkCore.InMemory
dotnet add package Microsoft.EntityFrameworkCore.Tools
2. Define Your Entity
Create a simple Blog
class. This will be our entity.
// Blog.cs
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
}
By convention, EF Core will recognize BlogId
as the primary key.
3. Create Your DbContext
Now, create your DbContext
class. This class will inherit from Microsoft.EntityFrameworkCore.DbContext
.
// BloggingContext.cs
using Microsoft.EntityFrameworkCore;
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// For this example, we're using the in-memory database.
// In a real app, you'd configure your connection string here.
optionsBuilder.UseInMemoryDatabase("BloggingDb");
}
}
4. Use Your Context to Interact with the Database
Now you can use your BloggingContext
to perform CRUD (Create, Read, Update, Delete) operations.
// Program.cs
using System;
using System.Linq;
Console.WriteLine("Starting EF Core example...");
// The 'using' statement ensures the context is properly disposed of.
using var db = new BloggingContext();
// Create a new blog
Console.WriteLine("Inserting a new blog");
db.Add(new Blog { Url = "http://blogs.msdn.com/adonet" });
db.SaveChanges(); // This is what actually executes the command against the database
// Read all blogs from the database
Console.WriteLine("Querying for a blog");
var blogs = db.Blogs.OrderBy(b => b.BlogId).ToList();
foreach (var blog in blogs)
{
Console.WriteLine($"- {blog.Url}");
}
// Update a blog
Console.WriteLine("Updating the blog and adding a post");
var firstBlog = db.Blogs.First();
firstBlog.Url = "https://devblogs.microsoft.com/dotnet";
db.SaveChanges();
// Delete a blog
Console.WriteLine("Delete the blog");
db.Remove(firstBlog);
db.SaveChanges();
Querying with LINQ
The real power of EF Core comes from its integration with LINQ (Language-Integrated Query). You can write complex queries in C#, and EF Core will translate them into efficient SQL.
// Get all blogs with 'dotnet' in the URL
var dotnetBlogs = db.Blogs
.Where(b => b.Url.Contains("dotnet"))
.ToList();
// Get a single blog by its ID
var specificBlog = db.Blogs.SingleOrDefault(b => b.BlogId == 1);
Migrations: Keeping Your Database in Sync
In a real application, your data model will change over time. EF Core Migrations is a powerful feature that allows you to update your database schema to match your C# entities.
To use migrations, you would typically use a real database provider (like Microsoft.EntityFrameworkCore.SqlServer
).
1. Add a Migration
This command inspects your entities and creates a new migration file with the C# code needed to update the database schema.
dotnet ef migrations add InitialCreate
2. Apply the Migration
This command runs the migration against your database, creating the tables and columns.
dotnet ef database update
Whenever you change your entity classes, you can just run dotnet ef migrations add <MigrationName>
again, and EF Core will figure out the changes needed.
Conclusion
Entity Framework Core is an essential tool for any .NET developer working with databases. It bridges the gap between your object-oriented C# code and the relational world of SQL. By handling the tedious work of data access, it allows you to focus on your application's business logic and build more robust, maintainable applications.