Entity Framework Core Basics
Entity Framework Core (EF Core) is a modern object-relational mapper (ORM) for .NET. It enables .NET developers to work with a database using .NET objects that map to the database schema. It eliminates the need for most of the data-access code that developers need to write.
What is an ORM?
An Object-Relational Mapper (ORM) is a type of middleware that is used to convert data between incompatible type systems within object-oriented programming languages. It bridges the gap between your object-oriented code and a relational database.
Key Concepts in EF Core
1. DbContext
The DbContext
is the primary class used when 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 add DbSet<TEntity>
properties for each entity in your model.
Example DbContext
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;");
}
}
2. Entities
Entities are plain old CLR objects (POCOs) that represent tables in your database. EF Core maps these objects to database tables. Properties on entity classes map to columns in the database.
Example Entities
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public ICollection<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; }
}
3. DbSet
A DbSet<TEntity>
represents a collection of all entities in the store for a given type. Think of it as a table in your database. You use DbSet
properties on your DbContext
to access and manipulate entities.
Common Operations
Creating the Database (Migrations)
EF Core uses Migrations to incrementally update your database schema as your domain model changes. This process involves generating migration files that contain C# code to describe the changes.
To enable Migrations, you'll typically install the EF Core tools:
dotnet tool install --global dotnet-ef
Then, you can add your first migration:
dotnet ef migrations add InitialCreate
dotnet ef database update
Querying Data
You can query data by accessing the DbSet
on your DbContext
and using LINQ (Language Integrated Query).
Querying Blogs
using var db = new BloggingContext();
var blogs = db.Blogs
.Where(b => b.Url.Contains("example.com"))
.OrderBy(b => b.Url);
foreach (var blog in blogs)
{
Console.WriteLine($" - {blog.Url}");
}
Adding Data
To add new entities, you create instances of your entity classes and add them to the appropriate DbSet
.
Adding a new Blog
using var db = new BloggingContext();
var newBlog = new Blog { Url = "http://newblog.example.com" };
db.Blogs.Add(newBlog);
db.SaveChanges(); // Persist changes to the database
Updating Data
To update an entity, retrieve it from the database, modify its properties, and then call SaveChanges()
.
Updating a Blog's URL
using var db = new BloggingContext();
var blogToUpdate = db.Blogs.FirstOrDefault(b => b.Url == "http://newblog.example.com");
if (blogToUpdate != null)
{
blogToUpdate.Url = "http://updatedblog.example.com";
db.SaveChanges();
}
Deleting Data
To delete an entity, retrieve it from the database and then call Remove()
on the DbSet
.
Deleting a Blog
using var db = new BloggingContext();
var blogToDelete = db.Blogs.FirstOrDefault(b => b.Url == "http://updatedblog.example.com");
if (blogToDelete != null)
{
db.Blogs.Remove(blogToDelete);
db.SaveChanges();
}
Note: Always call SaveChanges()
on the DbContext
to persist any pending changes to the database.
Next Steps
This section covered the fundamental concepts of EF Core. For more advanced topics like relationships, complex queries, and performance optimization, please refer to the other documentation sections.