Skip to content
Skills Library
Programming · Building & coding

entity-framework-core

/entity-framework-core

Entity Framework Core with DbContext, migrations, LINQ queries, relationships, and performance optimization. Covers EF Core 8+ patterns. USE WHEN: user mentions "Entity Framework", "EF Core", "DbContext", "migrations", "LINQ", "EF relationships", "database first", "code first" DO NOT USE FOR: Prisma - use `prisma`, Drizzle - use `drizzle`, Spring Data JPA - use `spring-data-jpa`, Dapper (raw SQL)

Licence
MIT
Last repository change
21.10.2026

Assessment and security

95/ 100Class: good
Format25 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content30 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
1
Scripts
0
HTML comments
0
URLs in SKILL.md
0
Deprecation

No signals detected. Repository changed on 21.10.2026, without references to retired models or APIs.

Licence

MIT, open: use and modify while retaining author attribution.

What it does and when to use it

Entity Framework Core with DbContext, migrations, LINQ queries, relationships, and performance optimization. Covers EF Core 8+ patterns. USE WHEN: user mentions "Entity Framework", "EF Core", "DbContext", "migrations", "LINQ", "EF relationships", "database first", "code first" DO NOT USE FOR: Prisma - use `prisma`, Drizzle - use `drizzle`, Spring Data JPA - use `spring-data-jpa`, Dapper (raw SQL)

Triggers from the description

Entity FrameworkEF CoreDbContextmigrationsLINQEF relationshipsdatabase firstcode first
Original author description

Entity Framework Core with DbContext, migrations, LINQ queries, relationships, and performance optimization. Covers EF Core 8+ patterns. USE WHEN: user mentions "Entity Framework", "EF Core", "DbContext", "migrations", "LINQ", "EF relationships", "database first", "code first" DO NOT USE FOR: Prisma - use `prisma`, Drizzle - use `drizzle`, Spring Data JPA - use `spring-data-jpa`, Dapper (raw SQL)

How it works

  1. DbContext Setup
  2. Entity Configuration (Fluent API)
  3. Migrations
  4. LINQ Queries
  5. Repository Pattern
  6. Performance Tips
  7. Anti-Patterns
  8. Quick Troubleshooting
Original SKILL.md headings · 183 lines, 620 words
SKILL.md preview
---
name: entity-framework-core
description: |
  Entity Framework Core with DbContext, migrations, LINQ queries, relationships,
  and performance optimization. Covers EF Core 8+ patterns.

  USE WHEN: user mentions "Entity Framework", "EF Core", "DbContext", "migrations",
  "LINQ", "EF relationships", "database first", "code first"

  DO NOT USE FOR: Prisma - use `prisma`, Drizzle - use `drizzle`,
  Spring Data JPA - use `spring-data-jpa`, Dapper (raw SQL)
allowed-tools: Read, Grep, Glob, Write, Edit
---
# Entity Framework Core - Quick Reference

> **Deep Knowledge**: Use `mcp__documentation__fetch_docs` with technology: `entity-framework-core` for comprehensive documentation.

## DbContext Setup

```csharp
public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }

    public DbSet<User> Users => Set<User>();
    public DbSet<Order> Orders => Set<Order>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.ApplyConfigurationsFromAssembly(typeof(AppDbContext).Assembly);
    }
}

// Registration
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("Default")));
```

## Entity Configuration (Fluent API)

```csharp
public class UserConfiguration : IEntityTypeConfiguration<User>
{
    public void Configure(EntityTypeBuilder<User> builder)
    {
        builder.HasKey(u => u.Id);
        builder.Property(u => u.Name).IsRequired().HasMaxLength(100);
        builder.Property(u => u.Email).IsRequired().HasMaxLength(255);
        builder.HasIndex(u => u.Email).IsUnique();

        // Relationships
        builder.HasMany(u => u.Orders)
            .WithOne(o => o.User)
            .HasForeignKey(o => o.UserId)
            .OnDelete(DeleteBehavior.Cascade);

        // Value conversion
        builder.Property(u => u.Status)
            .HasConversion<string>();

        // Default values
        builder.Property(u => u.CreatedAt)
            .HasDefaultValueSql("GETUTCDATE()");
    }
}
```

## Migrations

```bash
# Add migration
dotnet ef migrations add InitialCreate

# Update database
dotnet ef database update

# Remove last migration (not applied)
dotnet ef migrations remove

# Generate SQL script
dotnet ef migrations script

# Revert to specific migration
dotnet ef database update MigrationName
```

## LINQ Queries

```csharp
// Basic queries
var user = await context.Users.FindAsync(id);
var users = await context.Users.Where(u => u.IsActive).ToListAsync();
var user = await context.Users.FirstOrDefaultAsync(u => u.Email == email);

// Projection
var dtos = await context.Users
    .Where(u => u.IsActive)
    .Select(u => new UserResponse(u.Id, u.Name, u.Email))
    .ToListAsync();

// Include related data
var usersWithOrders = await context.Users
    .Include(u => u.Orders)
    .ThenInclude(o => o.OrderItems)
    .ToListAsync();

// Pagination
var page = await context.Users
    .OrderBy(u => u.Name)
    .Skip((pageNumber - 1) * pageSize)
    .Take(pageSize)
    .ToListAsync();

// Aggregation
var count = await context.Users.CountAsync(u => u.IsActive);
var avgAge = await context.Users.AverageAsync(u => u.Age);
```

## Repository Pattern

```csharp
public interface IRepository<T> where T : class
{
    Task<T?> GetByIdAsync(int id);
    Task<IEnumerable<T>> GetAllAsync();
    Task AddAsync(T entity);
    void Update(T entity);
    void Remove(T entity);
    Task<bool> ExistsAsync(Expression<Func<T, bool>> predicate);
    Task SaveChangesAsync();
}

public class Repository<T> : IRepository<T> where T : class
{
    protected readonly AppDbContext _context;
    protected readonly DbSet<T> _dbSet;

    public Repository(AppDbContext context)
    {
        _context = context;
        _dbSet = context.Set<T>();
    }

    public async Task<T?> GetByIdAsync(int id) => await _dbSet.FindAsync(id);
    public async Task<IEnumerable<T>> GetAllAsync() => await _dbSet.ToListAsync();
    public async Task AddAsync(T entity) => await _dbSet.AddAsync(entity);
    public void Update(T entity) => _dbSet.Update(entity);
    public void Remove(T entity) => _dbSet.Remove(entity);
    public async Task<bool> ExistsAsync(Expression<Func<T, bool>> predicate)
        => await _dbSet.AnyAsync(predicate);
    public async Task SaveChangesAsync() => await _context.SaveChangesAsync();
}
```

## Performance Tips

| Tip | Implementation |
|-----|----------------|
| Use `AsNoTracking()` for read-only | `context.Users.AsNoTracking().ToListAsync()` |
| Use `Select` to project | Avoid loading full entities |
| Use `AsSplitQuery()` | Prevent cartesian explosion with includes |
| Use compiled queries | `EF.CompileAsyncQuery(...)` for hot paths |
| Batch operations | `ExecuteUpdateAsync` / `ExecuteDeleteAsync` (EF Core 7+) |

```csharp
// Bulk update (EF Core 7+)
await context.Users
    .Where(u => u.LastLoginAt < cutoff)
    .ExecuteUpdateAsync(u => u.SetProperty(x => x.IsActive, false));

// Bulk delete
await context.Users
    .Where(u => u.IsDeleted)
    .ExecuteDeleteAsync();
```

## Anti-Patterns

| Anti-Pattern | Why It's Bad | Correct Approach |
|--------------|--------------|------------------|
| Loading full entities for display | Memory waste, slow | Use `Select` projections |
| N+1 queries | Performance killer | Use `Include` or projections |
| Not using `AsNoTracking` | Unnecessary overhead | Use for read-only queries |
| Calling `SaveChanges` per entity | Slow batch operations | Call once after all changes |
| Using `DbContext` as singleton | Thread-safety issues | Use `AddDbContext` (Scoped) |

## Quick Troubleshooting

| Issue | Likely Cause | Solution |
|-------|--------------|----------|
| Tracking conflict | Entity already tracked | Use `AsNoTracking` or detach |
| Migration fails | Model mismatch | Check pending changes, rebuild |
| Slow query | Missing index | Add `HasIndex` in configuration |
| Lazy loading fails | Not configured | Use `Include` (explicit loading) |
| Concurrency conflict | Stale data | Add `[ConcurrencyCheck]` or `RowVersion` |

Versions

RepositoryScoreLicence
This page · claude-dev-suite/claude-dev-suite95MIT
managedcode/dotnet-skills100MIT
Tyler-R-Kendrick/agent-skills100MIT

Database snapshot: 13.11.2026 · package version ad9c8556110e (SHA-256 digest of the entire package)

Downloads in the last 30 days: 1 · ranking

Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 90neo-dotnet-ef-core
    Use this skill when the task involves Entity Framework Core models, DbContext, migrations, LINQ queries, change tracking, database providers, performance tuning, or data access review in .NET projects.
  • 100ef-core
    Entity Framework Core patterns for .NET 10. Covers DbContext configuration, migrations workflow, interceptors, compiled queries, ExecuteUpdateAsync, ExecuteDeleteAsync, value converters, and query optimization. Load this skill when working with databases, writing queries,…
  • 100spring-data-jpa
    Spring Data JPA for database access in Spring Boot applications. Covers repositories, entities, relationships, queries, pagination, and auditing. Based on production patterns from castellino and gestionale-presenze projects. USE WHEN: user mentions "JPA", "repository", "entity",…
  • 100ef-core-query-optimizer
    Analyze and optimize Entity Framework Core queries in .NET code. Use this skill whenever the user shares EF Core / LINQ-to-Entities code, a DbContext, a repository, or a slow query and wants it reviewed or sped up — or mentions N+1, lazy loading, AsNoTracking, slow EF queries,…
  • 100efcore-d2-db-diagram
    Generate D2 database diagrams from Entity Framework Core models. USE FOR: EF Core database diagram, Entity Framework Core ERD, DbContext diagram, C# entity relationship diagram, PostgreSQL schema visualization, generate .d2 file from EF Core entities, Fluent API mapping diagram,…
  • 100optimizing-ef-core-queries
    Review and optimize application data access that uses Entity Framework Core (EF Core). Use for EF Core performance and correctness reviews of services, repositories, imports, and background jobs: slow or memory-heavy queries, excessive round-trips, hidden SaveChanges, premature…

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.