ef-core-advanced-patterns
БесплатноБез исполняемых скриптовНе проверенMaster Entity Framework Core advanced patterns including change tracking optimization, lazy/eager/explicit loading strategies, query splitting, compiled…
от thapaliyabikendra★ 25 звёзд на GitHubОб этом скилле
Entity Framework Core Advanced Patterns
Master EF Core patterns for building high-performance, maintainable data access layers with PostgreSQL.
When to Use This Skill
- Optimizing database query performance
- Eliminating N+1 query problems
- Managing change tracking efficiently
- Implementing bulk operations
- Handling concurrency conflicts
- Working with PostgreSQL-specific features
- Debugging slow EF Core queries
- Optimizing memory usage
Core Concepts
1. Change Tracking Optimization
No-Tracking Queries for Read-Only Operations:
// Bad: Unnecessary tracking overhead
public async Task<List<PatientDto>> GetPatientsAsync()
{
var patients = await _dbContext.Patients.ToListAsync();
return _mapper.Map<List<PatientDto>>(patients);
}
// Good: No tracking for read-only queries
public async Task<List<PatientDto>> GetPatientsAsync()
{
var patients = await _dbContext.Patients
.AsNoTracking()
.ToListAsync();
return _mapper.Map<List<PatientDto>>(patients);
}
// Best: Configure no-tracking at query level or globally
public class ClinicDbContext : AbpDbContext<ClinicDbContext>
{
public ClinicDbContext(DbContextOptions<ClinicDbContext> options)
: base(options)
{
// Global no-tracking (opt-in tracking when needed)
ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
}
}
Identity Resolution:
// NoTrackingWithIdentityResolution: Tracks for query duration only
var patients = await _dbContext.Patients
.AsNoTrackingWithIdentityResolution()
.Include(p => p.Appointments)
.ThenInclude(a => a.Doctor)
.ToListAsync();
// Ensures same entity instances are used within this query
// But not tracked after query completes
Change Tracker Management:
public async Task ProcessLargeBatchAsync()
{
var patients = await _dbContext.Patients.ToListAsync();
foreach (var patient in patients)
{
// Process patient
patient.LastProcessedDate = DateTime.UtcNow;
// Every 100 entities, save and clear tracker
if (patients.IndexOf(patient) % 100 == 0)
{
await _dbContext.SaveChangesAsync();
_dbContext.ChangeTracker.Clear(); // Free memory
}
}
await _dbContext.SaveChangesAsync();
}
2. Loading Strategies
Eager Loading with Include:
// Basic Include
var appointments = await _dbContext.Appointments
.Include(a => a.Patient)
.Include(a => a.Doctor)
.ToListAsync();
// ThenInclude for nested navigation
var appointments = await _dbContext.Appointments
.Include(a => a.Patient)
.ThenInclude(p => p.MedicalRecords)
.Include(a => a.Doctor)
.ThenInclude(d => d.Specializations)
.ToListAsync();
// Filtered Include (EF Core 5+)
var doctors = await _dbContext.Doctors
.Include(d => d.Appointments.Where(a => a.Status == AppointmentStatus.Scheduled))
.ToListAsync();
// Multiple navigation properties
var patients = await _dbContext.Patients
.Include(p => p.Appointments)
.Include(p => p.MedicalRecords)
.Include(p => p.PrimaryDoctor)
.ToListAsync();
Explicit Loading:
// Load related entities on demand
var patient = await _dbContext.Patients
.FirstOrDefaultAsync(p => p.Id == patientId);
// Explicitly load appointments
await _dbContext.Entry(patient)
.Collection(p => p.Appointments)
.LoadAsync();
// Explicitly load with filtering
await _dbContext.Entry(patient)
.Collection(p => p.Appointments)
.Query()
.Where(a => a.AppointmentDate >= DateTime.Today)
.LoadAsync();
// Load and count without loading all data
var appointmentCount = await _dbContext.Entry(patient)
.Collection(p => p.Appointments)
.Query()
.CountAsync();
Lazy Loading (Use Sparingly):
// Enable lazy loading (requires proxies)
public class ClinicDbContext : AbpDbContext<ClinicDbContext>
{
public ClinicDbContext(DbContextOptions<ClinicDbContext> options)
: base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseLazyLoadingProxies();
}
}
// Virtual navigation properties enable lazy loading
public class Patient
{
public virtual ICollection<Appointment> Appointments { get; set; }
// WARNING: Can cause N+1 queries if not careful
}
3. Query Splitting
Avoid Cartesian Explosion:
// Bad: Single query with multiple includes causes cartesian explosion
var doctors = await _dbContext.Doctors
.Include(d => d.Appointments)
.Include(d => d.DoctorSchedules)
.Include(d => d.Specializations)
.ToListAsync();
// Results in: Doctors × Appointments × Schedules × Specializations rows
// Good: Split query to avoid cartesian product
var doctors = await _dbContext.Doctors
.Include(d => d.Appointments)
.Include(d => d.DoctorSchedules)
.Include(d => d.Spec
Установить ef-core-advanced-patterns в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл ef-core-advanced-patterns?
Master Entity Framework Core advanced patterns including change tracking optimization, lazy/eager/explicit loading strategies, query splitting, compiled queries, batch operations, optimistic concurrency, performance optimization, and PostgreSQL-specific features for .NET applications.
Как установить скилл ef-core-advanced-patterns?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл ef-core-advanced-patterns запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic