Entity Framework Core Basics
Welcome to the foundational guide to Entity Framework Core (EF Core). This section covers the essential concepts and practices needed to get started with EF Core, Microsoft's modern, cross-platform Object-Relational Mapper (ORM) for .NET.
What is Entity Framework Core?
EF Core is a lightweight and extensible version of the familiar Entity Framework data access technology. It enables .NET developers to work with a database using domain-specific objects that are essentially ADO.NET data and nothing more. It eliminates the need for most of the data-access code that developers traditionally need to write.
Core Concepts
1. DbContext
The DbContext
class is the primary class for interacting with EF Core. It represents a session with the database and allows you to query and save data. You typically create a class that inherits from DbContext
and includes a property for each entity (table) in your model.
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=EFCoreBasics;Trusted_Connection=True;");
}
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public List<Post> Posts { get; } = new List<Post>();
}
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; }
}
2. DbSet<TEntity>
A DbSet<TEntity>
represents a collection of all entities in the store (e.g., all rows in a database table) and can be used to query the database. It's the gateway to querying your data. In the example above, Blogs
and Posts
are instances of DbSet<Blog>
and DbSet<Post>
respectively.
3. Entity Model
The entity model is a set of plain old CLR objects (POCOs) that represent your database schema. EF Core maps these objects to tables in your database. Properties in your entity classes typically map to columns in the database tables. Conventions are used to infer mappings, but you can also explicitly configure them.
4. Provider
EF Core uses a database provider to translate LINQ queries into database-specific SQL and to execute those queries. Common providers include:
Microsoft.EntityFrameworkCore.SqlServer
(for SQL Server)Microsoft.EntityFrameworkCore.Sqlite
(for SQLite)Npgsql.EntityFrameworkCore.PostgreSQL
(for PostgreSQL)MySql.EntityFrameworkCore
(for MySQL)
You specify the provider in the OnConfiguring
method of your DbContext
or via dependency injection.
Getting Started: A Simple Workflow
- Install EF Core Packages: Add the necessary EF Core NuGet packages to your project. For example, if you're using SQL Server:
You'll also need the design-time package for migrations:dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Design
- Define Your Entities: Create C# classes that represent your data.
- Create Your DbContext: Define a class that inherits from
DbContext
and includesDbSet<TEntity>
properties. - Configure the DbContext: Specify the database provider and connection string.
- Create Migrations (Optional but Recommended): EF Core Migrations allow you to evolve your database schema over time as your entity model changes.
dotnet ef migrations add InitialCreate
dotnet ef database update
- Use the DbContext: Instantiate your
DbContext
and use it to query, add, update, or delete data.
DbContext
lifetimes in ASP.NET Core applications.
Example: Creating and Querying Data
Here's how you might use the BloggingContext
to add a new blog and retrieve all blogs:
using var context = new BloggingContext();
// Add a new blog
var newBlog = new Blog { Url = "http://example.com/blogs/new" };
context.Blogs.Add(newBlog);
context.SaveChanges(); // Persist changes to the database
// Query all blogs
var allBlogs = context.Blogs.ToList();
foreach (var blog in allBlogs)
{
Console.WriteLine($"Blog URL: {blog.Url}");
}
This basic understanding of DbContext
, DbSet
, and entity mapping will serve as a solid foundation for further exploration of EF Core's powerful features.