Entity Framework Core Core Concepts
Entity Framework Core (EF Core) is a modern object-relational mapper (ORM) for .NET. It allows developers to work with a database using .NET objects, eliminating the need for most of the data-access code they typically need to write. EF Core supports LINQ queries, change tracking, saving and retrieving data, and much more.
DbContext
The DbContext
class 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 inherits from DbContext
and add a DbSet<TEntity>
property for each entity 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=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; }
}
DbSet<TEntity>
A DbSet<TEntity>
property on your DbContext
represents a collection of all entities in the store for that type. DbSet<TEntity>
will typically be used to load entities from and save entities to the database.
Entities
Entities are simple .NET classes (Plain Old CLR Objects - POCOs) that represent the data in your database. EF Core can map these classes to database tables. Conventionally, entity types are defined as public classes with public properties. EF Core will automatically discover entity types by looking for public properties of type DbSet<TEntity>
on the DbContext
.
Migrations
Migrations are a feature of EF Core that allows you to incrementally update your database schema to match your object model. They are essentially scripts that EF Core generates based on changes you make to your entities. You can use the EF Core command-line tools or Package Manager Console to manage migrations.
Creating a Migration
To create a new migration, run the following command:
dotnet ef migrations add InitialCreate
To apply the migration to the database:
dotnet ef database update
Change Tracking
EF Core automatically tracks changes made to entities that are loaded into the DbContext
. When you call SaveChanges()
, EF Core determines which entities have been added, modified, or deleted and generates the appropriate SQL commands to persist those changes to the database.
Querying Data
EF Core supports querying data using LINQ (Language Integrated Query). You can write LINQ queries that are translated into SQL by EF Core. This allows for powerful and type-safe data retrieval.
Example Query
using var db = new BloggingContext();
// Query for all blogs
var blogs = db.Blogs.ToList();
// Query for a specific blog and its posts
var firstBlog = db.Blogs
.Include(b => b.Posts)
.FirstOrDefault(b => b.Url.Contains(" 2"));
if (firstBlog != null)
{
Console.WriteLine($"Found blog: {firstBlog.Url}");
foreach (var post in firstBlog.Posts)
{
Console.WriteLine($"- {post.Title}");
}
}
Relationships
EF Core supports defining relationships between entities, such as one-to-one, one-to-many, and many-to-many. These relationships can be configured using conventions or data annotations.
Relationship Configuration
You can use the HasMany
, WithOne
, HasOne
, and WithMany
methods in the OnModelCreating
method of your DbContext
to configure relationships. Alternatively, you can use data annotations like [ForeignKey]
and [InverseProperty]
on your entity properties.