EF Core API Reference
Welcome to the comprehensive API reference for Entity Framework Core (.NET).
DbContext
The DbContext
class is the primary gateway to interacting with your data in Entity Framework Core. It represents a session with the database and allows you to query and save data.
Creating a DbContext
You can create a DbContext
instance by deriving from the DbContext
class and defining a constructor that calls the base class constructor with options.
public class MyDbContext : DbContext
Example of a derived context:
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
public BloggingContext(DbContextOptions<BloggingContext> options)
: base(options) { }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=Blogging;Trusted_Connection=True;");
}
}
}
DbContext
Configuration
Configuration can be done in multiple ways:
- Overriding
OnConfiguring(DbContextOptionsBuilder optionsBuilder)
: For simple configurations or when the context is not managed by DI. - Using
AddDbContext
in Dependency Injection: The preferred method in modern .NET applications.
Change Tracking
EF Core automatically tracks changes made to entities loaded into the context. When SaveChanges()
is called, EF Core determines which entities have been added, modified, or deleted and generates the appropriate SQL commands.
You can inspect the state of entities using ChangeTracker
.
Entity Configuration
Defining how your .NET classes map to database tables and columns. This is crucial for EF Core to understand your data model.
Fluent API
The Fluent API provides a programmatic way to configure your model. It's generally more powerful and flexible than Data Annotations.
Configuration is typically done within the OnModelCreating(ModelBuilder modelBuilder)
method of your derived DbContext
.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>()
.Property(b => b.Url)
.IsRequired();
modelBuilder.Entity<Post>()
.HasOne(p => p.Blog)
.WithMany(b => b.Posts);
}
Data Annotations
Attributes from the System.ComponentModel.DataAnnotations
namespace can be used to configure your entities directly on the model classes.
public class Blog
{
public int BlogId { get; set; }
[Required]
public string Url { get; set; }
public virtual ICollection<Post> Posts { get; set; }
}
Querying Data
Retrieve data from your database using LINQ or raw SQL.
LINQ to Entities
The primary way to query data is by using Language Integrated Query (LINQ).
using var db = new BloggingContext();
var blogs = db.Blogs
.Where(b => b.Rating > 3)
.OrderBy(b => b.Url)
.ToList();
Raw SQL Queries
For scenarios where LINQ is not sufficient, you can execute raw SQL queries.
var blogs = db.Blogs.FromSqlRaw("SELECT * FROM Blogs WHERE SomeCondition = {0}", "value");
var posts = db.Posts.ExecuteSqlInterpolated($"UPDATE Posts SET Content = {newContent} WHERE PostId = {postId}");
Projection
Selecting specific properties to reduce the amount of data transferred from the database.
var blogUrls = db.Blogs.Select(b => b.Url).ToList();
Saving Changes
Persisting changes made to your entities back to the database.
Add, Update, and Delete
EF Core makes it easy to manage the lifecycle of your entities.
// Add
var newBlog = new Blog { Url = "http://newblog.com" };
db.Blogs.Add(newBlog);
await db.SaveChangesAsync();
// Update
var existingBlog = db.Blogs.Find(1);
existingBlog.Url = "http://updatedurl.com";
await db.SaveChangesAsync();
// Delete
var blogToDelete = await db.Blogs.FindAsync(2);
if (blogToDelete != null)
{
db.Blogs.Remove(blogToDelete);
await db.SaveChangesAsync();
}
Bulk Operations
EF Core provides extensions for efficient bulk insert, update, and delete operations.
See the Providers section for details on extensions.
Migrations
EF Core Migrations allow you to evolve your database schema over time as your application model changes.
Creating Migrations
Use the .NET CLI or Package Manager Console to create migrations.
.NET CLI: dotnet ef migrations add InitialCreate
Package Manager Console: Add-Migration InitialCreate
Applying Migrations
Apply pending migrations to your database.
.NET CLI: dotnet ef database update
Package Manager Console: Update-Database
Database Providers
EF Core supports various database systems through specific providers. You need to install the appropriate NuGet package for your target database.
- SQL Server:
Microsoft.EntityFrameworkCore.SqlServer
- SQLite:
Microsoft.EntityFrameworkCore.Sqlite
- Npgsql (PostgreSQL):
Npgsql.EntityFrameworkCore.PostgreSQL
- MySql.Data.EntityFrameworkCore:
MySql.Data.EntityFrameworkCore
- Cosmos DB:
Microsoft.EntityFrameworkCore.Cosmos
Many providers also offer additional features, such as bulk operations or specific SQL generation capabilities.
Advanced Topics
Explore more advanced features of EF Core:
- Concurrency Control: Handling race conditions when multiple users modify the same data.
- Transactions: Managing ACID properties for data consistency.
- Interceptors: Hooking into EF Core operations.
- Compiled Models: Improving startup performance by pre-compiling your model.
- EF Core Tools: Utilizing the command-line interface for various tasks.
For more in-depth information, please refer to the official Entity Framework Core documentation.