📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

You are migrating a data layer from Entity Framework 6 to EF Core on .NET 10. Which behaviour differences bite during the move? Cover EDMX models, lazy loading, client evaluation, cascade and relationship conventions, and how you would migrate safely.

Covers the practical EF6-to-EF Core differences: no EDMX or ObjectContext, lazy loading off by default, client evaluation removed in EF Core 3.0, query translation and split queries, conventions, cascade delete, many-to-many, stored procedure mapping, and running EF6 on .NET 10 as a stepping stone.

Mid-Level Theory Intermediate data-access ef-core ef6 lazy-loading legacy-migration

🎯 Key points

  • EF Core has no EDMX designer and no ObjectContext: reverse engineer with dotnet ef dbcontext scaffold
  • Lazy loading is opt-in in EF Core (proxies package or ILazyLoader); EF6 virtual navigations loaded silently
  • EF Core 3.0+ throws if a query can't be translated; EF Core 1.x/2.x silently evaluated on the client; EF6 DbFunctions/SqlFunctions need EF.Functions equivalents
  • Different SQL shapes; AsSplitQuery avoids cartesian explosion when including several collections
  • Conventions differ: cascade delete, table names (DbSet name vs pluralised entity), FK column names, decimal precision
  • Concurrency tokens ([Timestamp]/rowversion, ConcurrencyCheck) must be remapped and tested; DbUpdateConcurrencyException handling changes
  • EF6 6.5.x (6.5.2, April 2026, .NET 10 compatible) runs on modern .NET, so move the runtime first and the ORM second
  • Characterisation tests that compare results, query counts and captured SQL before switching

⏱ 30-second answer

EF Core is a rewrite, not EF7 of the same code. What bites: there is no EDMX or ObjectContext, so designer models must be reverse engineered (dotnet ef dbcontext scaffold) into code. Lazy loading is off by default, so code that relied on virtual navigations returns empty collections or nulls. Since EF Core 3.0, untranslatable LINQ throws instead of being evaluated on the client. The SQL it generates differs (joins, collection includes), and conventions differ (cascade delete, table names, decimal precision).

The safe path: EF6 6.5 runs on .NET 10, so move the app to modern .NET first, then swap EF6 for EF Core one bounded context at a time, behind tests that compare results. The trade-off: a two-step move takes longer but separates runtime risk from ORM risk.

🗣 Full answer (senior)

How I would answer this in an interview

"The first thing I'd say is that EF Core isn't a new version of EF6, it's a rewrite with similar APIs, so the code compiles more often than it behaves the same. The big ones are these. EDMX doesn't exist, so if the model is in a designer file, you reverse engineer it with dotnet ef dbcontext scaffold and then fix up names and relationships. Lazy loading is opt-in, so code that walked order.Customer.Address and quietly fired queries now gets null. Since EF Core 3.0, a query that can't be translated to SQL throws; EF6 also threw for unsupported methods, but code using SqlFunctions or DbFunctions has to move to EF.Functions. And concurrency tokens like a rowversion column need to be mapped again and tested, or you silently lose optimistic concurrency.

The SQL changes too. EF Core shapes queries differently, and a query that includes two collections can return a cartesian product: [5,000] orders with [10] lines and [5] payments each becomes [250,000] rows. AsSplitQuery() sends one query per collection instead. That's a performance difference, not a correctness one, so you only find it if you look at the SQL and the row counts.

The mistake I see is doing the runtime migration and the ORM migration in one go. EF6 6.5.x runs on modern .NET, and 6.5.2 added .NET 10 compatibility, so I move the app to .NET 10 with EF6 first, ship it, and then move to EF Core one DbContext or module at a time, with characterisation tests that compare query results, query counts and the SQL in logs. The senior line: separate the risks so when something breaks you know which change did it."


Differences that bite

Area EF6 EF Core (10) What to do
Model EDMX designer or Code First Code only (Fluent API, attributes) dotnet ef dbcontext scaffold, then refine
Context ObjectContext + DbContext DbContext only Port ObjectContext code
Lazy loading On for virtual navigations Off; opt in with UseLazyLoadingProxies() Add Include or projections; use proxies only as a temporary bridge
Untranslatable LINQ Throws (NotSupportedException) Throws since 3.0 (only the final projection may run client-side) Rewrite queries; project to DTOs
Database functions DbFunctions, SqlFunctions EF.Functions, HasDbFunction mapping Port each call
Collection includes One big join Single query by default; AsSplitQuery() option Use split queries for multiple collections
Concurrency [Timestamp], ConcurrencyMode.Fixed in EDMX [Timestamp]/IsRowVersion(), IsConcurrencyToken() Remap and add a test for the conflict path
Cascade delete Convention for required relationships Similar, plus client-side cascade of tracked entities Configure OnDelete explicitly
Many-to-many Implicit join table Supported since EF Core 5 (skip navigations) Map join table name explicitly to match schema
Inheritance TPH, TPT, TPC TPH, TPT (5+), TPC (7+) Keep the existing strategy; check TPT performance
Stored procedures Function imports, CUD mapping FromSql, ExecuteSql, sproc CUD mapping since EF Core 7 Map explicitly
Spatial DbGeography NetTopologySuite Port types
Migrations EF6 __MigrationHistory table New __EFMigrationsHistory Baseline the current schema as already applied

Production example

In a typical migration of a 150-entity EF6 model, scaffolding plus clean-up takes a couple of weeks, and most defects found in testing are lazy-loading nulls, changed decimal precision on scaffolded columns and a missing rowversion mapping. Running the old and new data layer side by side against a masked copy of production data and diffing outputs catches the remaining issues before cutover.

🔍 What the interviewer is checking

Checks that the candidate knows the real EF6-to-EF Core traps and has a safe, staged migration approach.

Green flags

  • Names EDMX, lazy loading and client evaluation correctly, with versions
  • Knows EF6 runs on modern .NET and suggests separating the steps
  • Mentions baselining migrations and mapping the existing schema explicitly
  • Uses characterisation tests and SQL comparison

Red flags

  • Thinks EF Core is a drop-in upgrade
  • Turns on lazy loading globally without discussing N+1
  • Lets EF Core generate migrations against an existing production schema

📚 Learn in depth

1. Why the behaviour differs

EF6 was built on ObjectContext and an Entity Data Model (CSDL/SSDL/MSL mapping, which the EDMX file contains). EF Core has a lightweight, code-based model built at start-up, a new LINQ pipeline (rebuilt in 3.0), and a provider model that pushes more of the work into SQL. Same ideas, different engine.

EF6:      LINQ → Expression → Command tree (EDM) → Provider SQL
EF Core:  LINQ → Expression → Query pipeline (nav expansion, translation) → SQL
                                                 └─ throws if not translatable (3.0+)

2. Lazy loading in detail

EF6 creates proxy subclasses for entities with virtual navigations and loads them on first access. That hides N+1 queries. EF Core leaves navigations empty unless you Include, explicitly Load, or turn on UseLazyLoadingProxies() (Microsoft.EntityFrameworkCore.Proxies) or inject ILazyLoader. Turning proxies on globally gives you back EF6 behaviour, and EF6's N+1 problems with it; serialising entities with lazy loading also triggers queries and cycles.

3. Client evaluation

EF Core 1.x and 2.x silently evaluated parts of a query in memory and logged a warning. EF Core 3.0 removed that: only the final Select projection may run client-side. EF6 always threw for untranslatable methods. So the risk during migration is not EF6 code becoming slow, but queries that used EF6-specific functions (DbFunctions, SqlFunctions, EntityFunctions) needing EF.Functions equivalents.

4. Schema and migrations

EF Core must map to the existing schema exactly. Scaffolding helps, but check:

  • table names (EF Core uses the DbSet property name; EF6 pluralised the entity name),
  • foreign key names and many-to-many join tables,
  • decimal(18,2) precision (EF Core warns if not configured),
  • datetime vs datetime2.

Then create an initial EF Core migration and mark it as applied (dotnet ef migrations add Baseline and empty its Up, or insert the history row), so EF Core doesn't try to recreate tables.

5. EF6 on .NET 10

EF6 6.4+ supports modern .NET (no EDMX designer in SDK-style projects; you keep the EDMX by referencing it as embedded resources, or move to Code First). This lets you migrate the runtime first.

Try it yourself

  1. Scaffold an existing database with dotnet ef dbcontext scaffold "<conn>" Microsoft.EntityFrameworkCore.SqlServer -o Data and compare the model to the EF6 one.
  2. Write a query that uses a C# method inside Where and see EF Core 10 throw; rewrite it to translate.
  3. Load an order with two collection Includes, log the SQL with LogTo(Console.WriteLine), then add AsSplitQuery() and compare row counts.
  4. Enable lazy loading proxies, serialise an entity to JSON, and count the queries in the log.
  5. Write a characterisation test that runs the same report through the EF6 and EF Core data layers and asserts equal results.

💻 Code

The same query in EF6 (relying on lazy loading) and EF Core 10 (explicit loading and projection).

// Before: EF6 on .NET Framework, lazy loading hides N+1 queries
public class Order
{
    public int Id { get; set; }
    public virtual Customer Customer { get; set; }            // virtual = lazy proxy in EF6
    public virtual ICollection<OrderLine> Lines { get; set; }
}

public decimal TotalForCustomer(string email)
{
    using (var db = new ShopContext())
    {
        var orders = db.Orders.Where(o => o.Customer.Email == email).ToList();
        return orders.Sum(o => o.Lines.Sum(l => l.Price * l.Quantity)); // one query per order
    }
}
// After: EF Core 10 on .NET 10, explicit and translated to one SQL query
namespace Shop.Data;

using Microsoft.EntityFrameworkCore;

public sealed class OrderTotals(ShopDbContext db)
{
    public Task<decimal> TotalForCustomerAsync(string email, CancellationToken ct) =>
        db.Orders
            .Where(o => o.Customer.Email == email)
            .SelectMany(o => o.Lines)
            .SumAsync(l => l.Price * l.Quantity, ct);  // SUM runs in SQL Server
}
// Mapping the existing schema exactly (names, precision, join table)
protected override void OnModelCreating(ModelBuilder b)
{
    b.Entity<Order>().ToTable("Orders");                  // EF6 pluralised; be explicit
    b.Entity<OrderLine>().Property(l => l.Price).HasPrecision(18, 2);
    b.Entity<Order>()
        .HasOne(o => o.Customer).WithMany()
        .HasForeignKey("Customer_Id")                     // EF6 default FK column name
        .OnDelete(DeleteBehavior.Restrict);               // don't rely on convention
}

⚠ Common mistakes

  • Mistake: Turning on lazy loading proxies globally and leaving them on. Why it is wrong: It brings back hidden N+1 queries and serialisation cycles. Instead: Use proxies only as a deliberate, time-boxed bridge on specific screens while you add Include or projections.
  • Mistake: Letting EF Core create a new initial migration that recreates tables. Why it is wrong: It fails or, worse, drops and recreates objects. Instead: Baseline the existing schema as already applied.
  • Mistake: Trusting scaffolded names and precision. Why it is wrong: Table, FK and many-to-many names or decimal precision may not match EF6's conventions. Instead: Compare the model with the live schema and map explicitly.
  • Mistake: Forgetting concurrency tokens. Why it is wrong: Without the rowversion mapping, updates silently overwrite each other. Instead: Map IsRowVersion() and test that a conflicting update throws DbUpdateConcurrencyException.
  • Mistake: Migrating runtime and ORM in one release. Why it is wrong: When results change you can't tell which change caused it. Instead: Move to .NET 10 with EF6 first, then to EF Core.
  • Mistake: Not comparing generated SQL. Why it is wrong: EF Core may shape queries differently, causing slowdowns or cartesian explosion with several collection includes. Instead: Capture SQL in tests, use AsSplitQuery() where needed, and check plans in Query Store after release.
  • Mistake: Porting SqlFunctions / DbFunctions calls blindly. Why it is wrong: They don't exist in EF Core. Instead: Use EF.Functions equivalents or map database functions with HasDbFunction.

🏛 Senior insight: trade-offs

The key judgement is when to move the ORM. EF6 on .NET 10 is supported and works, so the ORM move isn't urgent for most teams. Do it when you want EF Core-only features (compiled models, ExecuteUpdate, JSON columns, better performance) or when you are already reworking that part of the code. Move one bounded context or DbContext at a time; both ORMs can run in the same process against the same database during the transition.

Strategy When it fits Cost When not to
Stay on EF6 6.5 on .NET 10 Stable data layer, migration focus is the web tier Low Need EF Core features or performance
Context-by-context move to EF Core Large model, multiple modules Medium, spread out Tiny model where one switch is simpler
Big-bang ORM swap Small model with strong tests Low to medium Weak test coverage
Replace with Dapper for hot paths A few performance-critical queries Low As a general ORM replacement

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions lazy loading proxies Why: Checks they can diagnose the N+1 and serialisation problems lazy loading causes
    How to answer

    Both symptoms come from serialising lazy-loading entities. System.Text.Json reads every public property; each virtual navigation triggers a SQL query on first access (N+1), and back-references such as Order.Customer.Orders form a cycle, so the serialiser throws ("A possible object cycle was detected") or goes very deep.

    I diagnose by counting SQL commands per request (EF Core command logging or Application Insights dependencies), then fix it properly: project to a DTO with Select so the response shape is explicit and EF Core sends one query, and turn lazy loading off (or make lazy loads throw) so it can't come back.

    Setting ReferenceHandler.IgnoreCycles stops the exception but leaves the dozens of queries in place.

  2. When: Candidate mentions Include instead of lazy loading Why: Checks they know eager, explicit and lazy loading and filtered Include
    How to answer

    EF Core does not load navigation properties unless you ask. There are three ways:

    • Eager loading: Include(o => o.Lines).ThenInclude(l => l.Product) loads related data in the same query (LEFT JOINs), or in several with AsSplitQuery().
    • Explicit loading: await db.Entry(order).Collection(o => o.Lines).LoadAsync() loads one navigation later, on demand; .Query() lets you filter or count instead.
    • Lazy loading: with UseLazyLoadingProxies() and virtual navigations, the first access runs a query automatically.

    Filtered Include (EF Core 5+) lets you write Include(c => c.Orders.Where(o => o.IsOpen).OrderBy(o => o.PlacedAt).Take(5)).

    The trade-off: eager is predictable, explicit is precise, lazy is convenient but hides N+1 queries.

  3. When: Candidate mentions the migrations history table Why: Checks they can baseline a schema without destructive changes
    How to answer

    Scaffold or map the model to match the current schema exactly (watch decimal precision, column types, FK and index names that EF6 conventions produced). Create an initial EF Core migration and mark it as already applied without running it: either delete the generated body of Up/Down so the baseline is empty, or keep the generated code (useful for creating new dev databases) and insert its row into __EFMigrationsHistory on existing databases. Verify with a schema compare (SqlPackage/DACPAC or a migration script against a restored copy of production) that model and database match and that the next migration is empty. Rehearse the whole process in staging first. Keep the old EF6 __MigrationHistory table only for reference, never as a source of truth. From then on generate idempotent SQL scripts (dotnet ef migrations script --idempotent) that are reviewed and run by the pipeline, not by Database.Migrate() at start-up.

🛠 Real-world problems: how you handle them

Lazy-loading nulls and a slow report after moving from EF6 to EF Core
Situation
A [claims management] system with [about 120 entities] moved its data layer from EF6 to EF Core [version] on .NET 10. The release went to the [Australia East] staging environment ahead of a [quarter-end] cutover.
Signals
Testers reported blank customer names on several screens and a `NullReferenceException` spike in Application Insights. The monthly claims report went from [6 seconds] to [timing out at 30 seconds]. SQL logs showed one query returning [1.2 million] rows for a report that displays [5,000].
Investigation
Searched the code for `virtual` navigation properties accessed without `Include` and matched them to the null exceptions. Turned on EF Core logging (`LogTo` with sensitive data off) and captured the report's SQL, which joined two collection navigations in one query (cartesian explosion). Compared it with the EF6 SQL captured in the characterisation tests and checked the actual execution plan in SSMS and Query Store.
Resolution
Immediate: kept the release in staging and turned on lazy loading proxies for the two affected screens only, as a time-boxed bridge. Real fix: replaced entity loading with DTO projections and explicit `Include`s, added `AsSplitQuery()` to the report, and moved the aggregation into SQL. The report returned to [under 2 seconds].
Prevention
Characterisation tests now assert both results and query count per use case; an analyser rule flags new `virtual` navigation properties; a checklist item for every EF Core migration PR requires the captured SQL; Query Store regressions alert after release.

How to tell it (STAR)

**S:** We were moving [a claims system] from EF6 to EF Core on .NET 10, and staging testing found blank fields and a report that timed out. **T:** I owned the data layer migration and had [two weeks] before the planned cutover. **A:** I matched the null exceptions to navigations that EF6 used to lazy load, and captured the report's SQL, which showed a cartesian explosion from two collection includes. I added a time-boxed proxy bridge for two screens so testing could continue, then rewrote the queries as projections with split queries, and added tests that check query counts. **R:** The report went from [timing out] to [under 2 seconds], we cut over on schedule, and there were [zero] data-layer incidents in the first month.

↩ Usually asked after

More in Legacy Technologies

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me