Entity Framework Core

Entity Framework Core interview questions and answers

Entity Framework Core interview questions from the basics (DbContext, migrations, relationships) to performance traps and concurrency in real applications. Each answer explains the reasoning and shows a short example.

Mixed · 35 questions · Tap a question to see the answer.

New to this? Learn it step by step in the free Entity Framework Core course.

  1. Q1. What lifetime should a DbContext have in an ASP.NET Core app, and why is sharing one instance across threads a problem?

    Register it as Scoped with AddDbContext, so each HTTP request gets its own instance. A DbContext is a lightweight unit of work, not thread-safe, and it tracks every entity it loads.

    A shared or Singleton context fails with 'A second operation was started on this context instance' under concurrent use, and its change tracker grows without limit. In background services, create a scope or use IDbContextFactory<T> to create short-lived contexts.

    builder.Services.AddDbContextFactory<AppDbContext>(o => o.UseSqlServer(conn));
    
    // in a singleton/background service
    await using var db = await factory.CreateDbContextAsync(ct);

    Official documentation

  2. Q2. What does change tracking do, and when should you use AsNoTracking()?

    By default, entities returned by a query are tracked: EF Core keeps a snapshot and detects changes at SaveChanges. That costs memory and CPU.

    For read-only queries (API GETs, reports), use AsNoTracking() (or AsNoTrackingWithIdentityResolution() if you need one instance per key). For whole read-heavy contexts, set QueryTrackingBehavior.NoTracking as the default.

    var products = await db.Products
        .AsNoTracking()
        .Where(p => p.IsActive)
        .ToListAsync(ct);

    Official documentation

  3. Q3. Compare eager, explicit and lazy loading of related data.

    Eager loading (Include/ThenInclude) loads related data in the same query. Explicit loading (db.Entry(order).Collection(o => o.Lines).LoadAsync()) loads it later on demand. Lazy loading (proxies) loads a navigation automatically the first time it is accessed.

    Lazy loading easily causes N+1 queries, especially during JSON serialization, so most web APIs avoid it and use projections or Include instead.

    var orders = await db.Orders
        .Include(o => o.Customer)
        .Include(o => o.Lines).ThenInclude(l => l.Product)
        .Where(o => o.Id == id)
        .ToListAsync(ct);

    Official documentation

  4. Q4. A query with two collection Includes returns slowly and transfers far more data than expected. What is happening?

    Including two collections in one query joins them, so each order row is repeated for every combination of lines × payments: a cartesian explosion.

    Use AsSplitQuery() to load each collection with its own SQL query, or project only the data you need. Split queries cost extra round trips and can see inconsistent data if rows change between them; you can set split queries as the default for the context.

    var orders = await db.Orders
        .Include(o => o.Lines)
        .Include(o => o.Payments)
        .AsSplitQuery()
        .ToListAsync(ct);

    Official documentation

  5. Q5. Why is projecting to a DTO with Select often better than returning entities from an API?

    Select makes EF Core fetch only the columns you use, joins related data in SQL without Include, and returns untracked results. It also avoids exposing your database model and serialization cycles.

    Entity graphs returned directly from an API often cause over-fetching, lazy loading surprises, or cycles in JSON.

    var dto = await db.Orders
        .Where(o => o.Id == id)
        .Select(o => new OrderDto(o.Id, o.Total, o.Customer.Name, o.Lines.Count))
        .SingleOrDefaultAsync(ct);

    Official documentation

  6. Q6. How should you apply EF Core migrations to a production database?

    Not with Database.Migrate() at app startup: several instances may race, and the app needs schema-change permissions. Generate an idempotent SQL script (dotnet ef migrations script --idempotent) or a migration bundle (dotnet ef migrations bundle) and run it as a deployment step.

    Review the generated SQL, especially for renames (EF may drop and add a column) and data-losing changes.

    dotnet ef migrations bundle --self-contained -r linux-x64
    ./efbundle --connection "$CONNECTION_STRING"

    Official documentation

  7. Q7. Two users edit the same product at the same time and one silently overwrites the other. How does EF Core prevent this?

    Add a concurrency token, for example a SQL Server rowversion column mapped with [Timestamp]. EF Core adds it to the UPDATE's WHERE clause; if another user changed the row, zero rows are affected and EF throws DbUpdateConcurrencyException.

    Catch it and decide: reload and show the user the new values, retry, or merge.

    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; } = "";
        [Timestamp] public byte[] Version { get; set; } = [];
    }

    Official documentation

  8. Q8. How do you update or delete thousands of rows efficiently in EF Core 7+?

    Use ExecuteUpdateAsync and ExecuteDeleteAsync. They translate to a single UPDATE or DELETE statement and run immediately without loading entities into memory.

    They bypass the change tracker, so tracked entities in the same context aren't updated, and they don't run in the same transaction as SaveChanges unless you open one explicitly.

    await db.Orders
        .Where(o => o.Status == Status.Draft && o.CreatedAt < cutoff)
        .ExecuteDeleteAsync(ct);
    
    await db.Products
        .Where(p => p.CategoryId == id)
        .ExecuteUpdateAsync(s => s.SetProperty(p => p.Price, p => p.Price * 1.1m), ct);

    Official documentation

  9. Q9. When and how do you use raw SQL with EF Core safely?

    Use it for queries LINQ can't express well or for tuned SQL. FromSql with an interpolated string turns each interpolated value into a parameter, so it is safe from SQL injection; you can compose LINQ on top of it.

    FromSqlRaw with string concatenation is not safe. SqlQuery<T> (EF Core 8+) maps results to unmapped types such as DTOs.

    var term = "%" + search + "%";
    var blogs = await db.Blogs
        .FromSql($"SELECT * FROM dbo.Blogs WHERE Name LIKE {term}")
        .Where(b => b.IsActive)
        .ToListAsync(ct);

    Official documentation

  10. Q10. A LINQ query throws 'could not be translated' at runtime. Why, and how do you fix it?

    EF Core must translate the whole Where/OrderBy to SQL. Calling a custom C# method or an unsupported function inside it can't be translated, and since EF Core 3.0 it throws instead of silently loading everything into memory.

    Rewrite the condition with translatable operations, move the custom logic after a projection to the final Select, or explicitly switch to client evaluation with AsEnumerable() after filtering as much as possible in SQL.

    Official documentation

  11. Q11. How do you map a value object like an Address that has no identity of its own?

    Use an owned type (OwnsOne) or, in EF Core 8+, a complex type (ComplexProperty). Both store the properties in the owner's table (Address_Street, Address_City...).

    Complex types are the better fit for true value objects: they have no key and can be shared by value. Owned types are still entity types with a hidden key, and can also map to a separate table or JSON column.

    modelBuilder.Entity<Customer>().ComplexProperty(c => c.Address);

    Official documentation

  12. Q12. Your API runs the same EF Core query thousands of times per second. What can reduce EF overhead?

    Use DbContext pooling (AddDbContextPool), which reuses context instances instead of creating new ones, and compiled queries (EF.CompileAsyncQuery), which skip LINQ translation on each call.

    Measure first: usually indexes, projections and no-tracking matter far more. Pooled contexts must not keep per-request state in fields.

    private static readonly Func<AppDbContext, int, Task<Product?>> ById =
        EF.CompileAsyncQuery((AppDbContext db, int id) =>
            db.Products.AsNoTracking().FirstOrDefault(p => p.Id == id));

    Official documentation

  13. Q13. What is Entity Framework Core, and what is an ORM?

    An ORM (object-relational mapper) lets you work with database tables as C# classes. Entity Framework Core is Microsoft's ORM for .NET: you write LINQ queries against DbSet<T> properties and EF Core turns them into SQL, then turns the rows back into objects.

    It supports SQL Server, PostgreSQL, SQLite, MySQL, Cosmos DB and others through providers, tracks changes to loaded objects, and can create and update the database schema with migrations.

    Official documentation

  14. Q14. What are DbContext and DbSet?

    DbContext represents a session with the database: it holds the connection settings, tracks the entities you load and saves changes with SaveChanges. DbSet<T> represents one table and is where LINQ queries start.

    You create a class that inherits from DbContext, add a DbSet<T> property per entity, and register it with AddDbContext in Program.cs.

    public class ShopDbContext(DbContextOptions<ShopDbContext> options) : DbContext(options)
    {
        public DbSet<Product> Products => Set<Product>();
        public DbSet<Order> Orders => Set<Order>();
    }
    
    builder.Services.AddDbContext<ShopDbContext>(o =>
        o.UseSqlServer(builder.Configuration.GetConnectionString("Shop")));
  15. Q15. What is the difference between code-first and database-first?

    In code-first, you write the entity classes and configuration in C#, and migrations create or change the database to match. It suits new projects where the team owns the schema.

    In database-first, the database already exists and you generate the classes from it with dotnet ef dbcontext scaffold. It suits existing databases managed by a DBA. Many teams start database-first for a legacy database and then switch to migrations.

  16. Q16. How do EF Core migrations work?

    After changing your model, run dotnet ef migrations add Name. EF Core compares the model with a snapshot of the previous one and writes a migration class with Up and Down methods. dotnet ef database update applies pending migrations, and the __EFMigrationsHistory table records which ones ran.

    Always read the generated migration before applying it, because a rename can appear as a drop and an add, which loses data.

    dotnet ef migrations add AddProductSku
    dotnet ef database update
    # SQL script for review or production:
    dotnet ef migrations script --idempotent -o migrate.sql
  17. Q17. What is the difference between data annotations and the Fluent API?

    Data annotations are attributes on the entity, such as [Required] or [MaxLength(100)]. They are quick and also used by ASP.NET Core validation.

    The Fluent API configures the model in OnModelCreating or IEntityTypeConfiguration<T> classes. It can do everything annotations can and more: composite keys, indexes, relationships, precision and value conversions. It also keeps database details out of the entity classes. When both are used, the Fluent API wins.

    modelBuilder.Entity<Product>(e =>
    {
        e.Property(p => p.Name).HasMaxLength(100).IsRequired();
        e.Property(p => p.Price).HasPrecision(10, 2);
        e.HasIndex(p => p.Sku).IsUnique();
    });
  18. Q18. How do you configure one-to-many and many-to-many relationships?

    For one-to-many, give the principal a collection navigation (Customer.Orders) and the dependent a reference and foreign key (Order.CustomerId, Order.Customer). EF Core finds the relationship by convention.

    For many-to-many, put a collection on both sides (Post.Tags and Tag.Posts). EF Core creates the join table automatically. Add a join entity class only when the join needs extra columns, such as the date a tag was added.

  19. Q19. Is SaveChanges transactional, and when do you need an explicit transaction?

    Yes. All changes in one SaveChanges call are sent in a single database transaction, so either all succeed or none do.

    Use an explicit transaction with Database.BeginTransactionAsync() when one unit of work needs several SaveChanges calls, or mixes EF Core with raw SQL, and all of it must succeed or fail together.

    await using var tx = await db.Database.BeginTransactionAsync(ct);
    db.Orders.Add(order);
    await db.SaveChangesAsync(ct);
    await db.Database.ExecuteSqlInterpolatedAsync($"EXEC ReserveStock {order.Id}", ct);
    await tx.CommitAsync(ct);
  20. Q20. What entity states does the change tracker use?

    Each tracked entity has a state: Added (will be inserted), Unchanged (loaded and not modified), Modified (will be updated), Deleted (will be deleted) or Detached (not tracked).

    SaveChanges turns these states into INSERT, UPDATE and DELETE statements. You can see them with db.ChangeTracker.DebugView.LongView, which helps when an update does not save or saves too much.

  21. Q21. What is the difference between Find and FirstOrDefault?

    Find looks up an entity by primary key and first checks the entities the context is already tracking. If found there, no database query runs at all.

    FirstOrDefault always runs a query and can filter on any condition and include related data. Use Find or FindAsync for simple key lookups and FirstOrDefaultAsync with Where and Include for everything else.

  22. Q22. What are global query filters, and what are they used for?

    A global query filter is a condition added in OnModelCreating that EF Core applies to every query for that entity. Typical uses are soft delete (!IsDeleted) and multi-tenant apps (TenantId == currentTenant).

    Call IgnoreQueryFilters() on a query when you really need the hidden rows, for example in an admin screen that restores deleted items.

    modelBuilder.Entity<Order>().HasQueryFilter(o => !o.IsDeleted);
    
    // later
    var deleted = await db.Orders.IgnoreQueryFilters().Where(o => o.IsDeleted).ToListAsync();
  23. Q23. How do you see the SQL that EF Core generates?

    Enable logging: EF Core writes every command to the Microsoft.EntityFrameworkCore.Database.Command log category at Information level. In development, LogTo(Console.WriteLine) in the options is the quickest way.

    For one query, ToQueryString() returns the SQL without running it. Checking the SQL is the first step when a query is slow or returns unexpected rows.

    var query = db.Orders.Where(o => o.Total > 1000).OrderBy(o => o.Date);
    Console.WriteLine(query.ToQueryString());
  24. Q24. When would you use Dapper or raw ADO.NET instead of EF Core?

    EF Core gives you change tracking, migrations, LINQ and relationships, which makes everyday CRUD fast to write. Dapper is a thin mapper over hand-written SQL with very little overhead.

    Many teams use EF Core for most of the app and Dapper (or EF Core's own SqlQuery) for a few complex or very hot reporting queries where full control of the SQL matters. Either way, always pass values as parameters to avoid SQL injection.

  25. Q25. How do you seed data with EF Core?

    Fixed reference data, such as countries or order statuses, can be added with HasData in OnModelCreating. It becomes part of migrations, so keys must be set explicitly.

    For larger or environment-specific data, such as a demo admin user, run seeding code at startup or with a separate tool, and make it safe to run twice by checking whether the data already exists.

    modelBuilder.Entity<OrderStatus>().HasData(
        new OrderStatus { Id = 1, Name = "Pending" },
        new OrderStatus { Id = 2, Name = "Shipped" });
  26. Q26. How does EF Core map class inheritance to tables: TPH, TPT and TPC?

    Table-per-hierarchy (TPH, the default) stores every class in one table with a discriminator column. It is the fastest to query but has many nullable columns.

    Table-per-type (TPT) gives each class its own table joined by the key: a clean schema, but queries need joins and are slower.

    Table-per-concrete-type (TPC) gives each concrete class a full table with all its columns: no joins for a single type, but querying the base type needs UNION ALL, and keys must be unique across tables. Start with TPH unless you have a clear reason not to.

    modelBuilder.Entity<Payment>().UseTpcMappingStrategy();
    // or .UseTptMappingStrategy(); TPH needs no call

    Official documentation

  27. Q27. What are value converters in EF Core? Give an example.

    A value converter changes how a property is stored in the database and converts it back when reading. The classic examples are storing an enum as a string instead of a number, or a strongly typed id such as CustomerId as an int.

    Be careful when filtering on converted properties: the comparison happens on the stored value, so some LINQ expressions cannot be translated.

    modelBuilder.Entity<Order>()
        .Property(o => o.Status)
        .HasConversion<string>()
        .HasMaxLength(20);

    Official documentation

  28. Q28. What are shadow properties, and when are they useful?

    A shadow property exists in the EF model and the database table but not on your .NET class. You read and write it through EF.Property<T>(entity, "Name") or the change tracker.

    They are useful for data the domain class should not carry, such as audit columns like LastUpdated set automatically in SaveChanges, or foreign key columns when the class only has a navigation property.

    modelBuilder.Entity<Blog>().Property<DateTime>("LastUpdated");
    
    var recent = db.Blogs.OrderByDescending(b => EF.Property<DateTime>(b, "LastUpdated"));

    Official documentation

  29. Q29. What are EF Core interceptors used for?

    Interceptors let you run code when EF Core does certain things: before or after a command is executed, when a connection opens, or when SaveChanges runs.

    Common uses: setting audit fields or soft-delete flags in a SaveChangesInterceptor, adding query hints, logging slow commands, or setting a token on the connection. Register them with AddInterceptors when configuring the DbContext.

    public class AuditInterceptor : SaveChangesInterceptor
    {
        public override ValueTask<InterceptionResult<int>> SavingChangesAsync(
            DbContextEventData e, InterceptionResult<int> result, CancellationToken ct = default)
        {
            foreach (var entry in e.Context!.ChangeTracker.Entries<IAudited>())
                if (entry.State is EntityState.Added or EntityState.Modified)
                    entry.Entity.UpdatedAt = DateTime.UtcNow;
            return base.SavingChangesAsync(e, result, ct);
        }
    }

    Official documentation

  30. Q30. How do you handle transient database errors, for example on Azure SQL, with EF Core?

    Cloud databases sometimes drop connections or throttle for a few seconds. Turn on the provider's retrying execution strategy with EnableRetryOnFailure() so EF Core retries failed operations automatically.

    If you use your own transaction with retries on, wrap the whole unit of work in db.Database.CreateExecutionStrategy().ExecuteAsync(...), because EF cannot safely retry half of a user-started transaction.

    builder.Services.AddDbContext<AppDb>(o =>
        o.UseSqlServer(conn, sql => sql.EnableRetryOnFailure(maxRetryCount: 5)));

    Official documentation

  31. Q31. How do you store a JSON document in a column with EF Core?

    Map an owned type or complex type to a JSON column with ToJson(). EF Core serializes the object into one column, and you can still query inside it with LINQ, which is translated to the database's JSON functions.

    It suits data that belongs to one row and has a flexible shape, such as settings or an address list. Use normal tables when you need foreign keys, joins or constraints on that data.

    modelBuilder.Entity<Customer>().OwnsOne(c => c.Preferences, b => b.ToJson());
    
    var darkMode = await db.Customers
        .Where(c => c.Preferences.Theme == "dark").ToListAsync();

    Official documentation

  32. Q32. What are keyless entity types, and when do you use them?

    A keyless entity has no primary key, so EF Core can read it but never tracks, inserts or updates it. Configure it with HasNoKey() or [Keyless].

    Use keyless entities for read-only results such as database views, reporting queries from FromSql, or functions that return tables.

    modelBuilder.Entity<SalesSummary>()
        .HasNoKey()
        .ToView("vw_SalesSummary");

    Official documentation

  33. Q33. Why is Skip/Take paging slow on deep pages, and what is the alternative in EF Core?

    Skip(10000).Take(20) makes the database read and throw away 10,000 rows on every request, so later pages get slower, and rows can be skipped or repeated if data changes between requests.

    Keyset paging remembers the last key of the previous page and asks for rows after it, which uses an index seek and stays fast on any page. The trade-off is that you cannot jump straight to page 500.

    var page = await db.Posts
        .OrderBy(p => p.Id)
        .Where(p => p.Id > lastId)
        .Take(20)
        .ToListAsync();

    Official documentation

  34. Q34. How do you define indexes in EF Core, and how do you know which ones you need?

    Define them with HasIndex in the Fluent API or the [Index] attribute on the class. Mark unique ones with IsUnique(), use composite indexes for queries that filter on several columns, and use filters for partial indexes.

    Decide from real queries: log the SQL EF generates, look at the execution plans of slow queries, and index the columns used in WHERE, JOIN and ORDER BY. Too many indexes slow down inserts and updates, so add them for measured needs.

    modelBuilder.Entity<Order>()
        .HasIndex(o => new { o.CustomerId, o.CreatedAt });
    
    modelBuilder.Entity<User>()
        .HasIndex(u => u.Email).IsUnique();

    Official documentation

  35. Q35. How should you test code that uses EF Core?

    The EF Core in-memory provider is not a real relational database: it ignores transactions, constraints and SQL translation, so tests can pass while production fails. Microsoft discourages it for testing.

    Better options: test against the same database engine, for example SQL Server in a Docker container with Testcontainers, for queries and repositories; or use a repository interface and mock it to unit-test business logic. SQLite in-memory is a middle ground but still behaves differently from SQL Server.

    Official documentation

Original questions written to explain concepts; not taken from any certification exam. Spotted a mistake? See our corrections policy.