EF Core Advanced Topics
This section covers more advanced concepts and patterns for using Entity Framework Core (EF Core) effectively in your .NET applications. Explore these topics to optimize performance, handle complex scenarios, and deepen your understanding of EF Core's capabilities.
1. Performance Optimization
Achieving peak performance with EF Core is crucial for scalable applications. This topic delves into strategies such as:
- Efficient querying techniques (e.g., projection, lazy loading vs. eager loading).
- Understanding and optimizing database indexing.
- Batch operations for INSERT, UPDATE, and DELETE statements.
- Using
AsNoTracking()
for read-only scenarios. - Connection resiliency and retry policies.
Example: Projection for performance
var products = await context.Products
.Where(p => p.Category == "Electronics")
.Select(p => new { p.Name, p.Price }) // Only select needed columns
.ToListAsync();
2. Concurrency Control
Handling concurrent data modifications is essential to prevent data loss and maintain data integrity. We cover:
- Optimistic concurrency using row versioning or timestamp columns.
- Detecting and handling concurrency conflicts.
- Strategies for resolving conflicts (e.g., overwrite, merge, abort).
Example: Optimistic concurrency setup
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
[Timestamp] // Or use a decimal/int for row versioning
public byte[] Timestamp { get; set; }
}
3. Advanced Querying and Mapping
Beyond basic LINQ queries, EF Core offers powerful features for complex data retrieval and mapping:
- Using raw SQL queries with
FromSqlRaw()
andExecuteSqlRaw()
. - Complex type mapping and value objects.
- Owned entities for complex property types.
- Table-per-type, table-per-hierarchy, and table-per-concrete-type inheritance mapping.
- Mapping to existing databases (database-first approach).
4. Global Query Filters
Apply filters to all queries of a specific entity type globally. This is often used for soft deletes or multi-tenancy.
// In DbContext configuration:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>().HasQueryFilter(b => !b.IsDeleted);
}
5. Interceptors
Interceptors allow you to hook into EF Core's operations (like query execution, saving changes, or opening connections) to modify behavior or log information.
DbCommandInterceptor
for logging or modifying SQL commands.SaveChangesInterceptor
for custom logic before/after saving changes.
6. Extensibility and Customization
Learn how to extend EF Core's functionality:
- Custom convention builders.
- Custom data types and type mapping.
- Implementing custom `IConventionAnnotation` providers.
7. Migrations in Production
Strategies for safely applying database schema changes in a production environment.
- Automated migrations.
- Zero-downtime deployments with migrations.
- Rollback strategies.
Continue learning and mastering EF Core by exploring these advanced topics.