Getting Started with Entity Framework Core
Welcome to the Getting Started guide for Entity Framework Core (EF Core)! EF Core is a modern object-relational mapper (ORM) for .NET that enables developers to work with a database using .NET objects that map to the database schema.
This guide will walk you through the fundamental concepts and common tasks required to use EF Core effectively.
Prerequisites
Before you begin, ensure you have the following installed:
- .NET SDK (version 6.0 or later recommended)
- A code editor like Visual Studio, VS Code, or Rider
Installation
You can install EF Core using the .NET CLI. For example, to add the core EF Core package and a provider for SQL Server:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
You will also need the tools package for migrations:
dotnet add package Microsoft.EntityFrameworkCore.Tools
Core Concepts
1. DbContext
The DbContext
is the primary class used to interact with the database. It represents a session with the database and can be used to query and save data. You typically create a class that derives from DbContext
and add a DbSet<TEntity>
property for each entity in your model.
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;");
}
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public virtual ICollection<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 virtual Blog Blog { get; set; }
}
2. Entities
Entities are regular .NET classes that represent the data you want to store in the database. EF Core can infer a schema from your entity classes.
3. Migrations
EF Core Migrations allow you to incrementally update your database schema to match your entity model without having to manually write SQL scripts. You can create new migrations and apply them to your database using the .NET CLI or Package Manager Console.
To create an initial migration:
dotnet ef migrations add InitialCreate
To apply migrations to the database:
dotnet ef database update
Common Scenarios
Creating and Querying Data
Here's a simple example of how to use the DbContext
to add and query data:
using var context = new BloggingContext();
// Create a new blog
var blog = new Blog { Url = "http://blogs.example.com" };
context.Blogs.Add(blog);
context.SaveChanges();
// Query for all blogs
var blogs = context.Blogs.ToList();
// Query for blogs with a specific URL
var exampleBlogs = context.Blogs
.Where(b => b.Url.Contains("example.com"))
.ToList();
Next Steps
This guide covered the absolute basics. To dive deeper, explore the following: