Entity Framework Core Basics
This document introduces the fundamental concepts and core features of Entity Framework Core (EF Core), a modern object-relational mapper (ORM) for .NET. EF Core allows developers to work with databases using .NET objects, abstracting away much of the complexity of direct SQL interaction.
What is Entity Framework Core?
EF Core provides a set of .NET APIs that enable developers to manage data access operations. It bridges the gap between your object-oriented code and the relational databases you interact with. Key benefits include:
- Productivity: Reduces boilerplate data access code.
- Maintainability: Code is cleaner and easier to understand.
- Database Agnosticism: Works with various database providers (SQL Server, PostgreSQL, MySQL, SQLite, etc.).
- Type Safety: Leverages C# types for database operations.
Core Concepts
Understanding these core concepts is crucial for effectively using EF Core:
DbContext
The DbContext
is the primary class that represents a session with the database and enables you to query and save data. It's a bridge between your domain objects and the database. You'll typically inherit from DbContext
and define properties of type DbSet<TEntity>
for each entity you want to persist.
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("YourConnectionString");
}
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public 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 Blog Blog { get; set; }
}
DbSet<TEntity>
A DbSet<TEntity>
represents a collection of all entities in the store (e.g., all blogs in the database) and can be used to query the entity type. It's the gateway to querying your data.
Entities
Entities are your plain old C# objects (POCOs) that represent the data you store in your database. EF Core maps these objects to tables in your database.
Migrations
Migrations are a feature of EF Core that allows you to incrementally update your database schema to match your evolving data model without having to manually write and maintain versioned SQL scripts. EF Core generates these scripts for you.
Common Operations
Here are some common operations you'll perform with EF Core:
Adding Data
To add a new entity, you first create an instance of your entity class, add it to the appropriate DbSet
on your DbContext
, and then call SaveChanges
.
using var context = new BloggingContext();
var newBlog = new Blog { Url = "http://example.com/blog" };
context.Blogs.Add(newBlog);
context.SaveChanges();
Querying Data
You can query entities using LINQ (Language Integrated Query). EF Core translates your LINQ queries into SQL.
using var context = new BloggingContext();
var blogs = context.Blogs
.Where(b => b.Url.Contains("example.com"))
.OrderBy(b => b.Url)
.ToList();
foreach (var blog in blogs)
{
Console.WriteLine($"Found blog: {blog.Url}");
}
Updating Data
To update an existing entity, you retrieve it from the database, modify its properties, and then call SaveChanges
. EF Core tracks changes automatically.
using var context = new BloggingContext();
var blogToUpdate = context.Blogs.FirstOrDefault(b => b.BlogId == 1);
if (blogToUpdate != null)
{
blogToUpdate.Url = "http://updated-example.com/blog";
context.SaveChanges();
}
Deleting Data
To delete an entity, you retrieve it from the database, remove it from the appropriate DbSet
, and then call SaveChanges
.
using var context = new BloggingContext();
var blogToDelete = context.Blogs.FirstOrDefault(b => b.BlogId == 2);
if (blogToDelete != null)
{
context.Blogs.Remove(blogToDelete);
context.SaveChanges();
}
DbContext
instances when you are finished with them, typically by using a using
statement. This releases database connections and other resources.
Next Steps
This document covered the very basics of EF Core. To delve deeper, explore the following topics: