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

📚 Interview question

Your .NET Framework app uses EF6 against an on-premises SQL Server, and you're moving it to .NET 10 on Azure. How do you migrate the database side alongside the app: running EF6 and EF Core against the same schema during the transition, moving the data to Azure SQL, handling data migrations, and planning the cutover and rollback?

Covers the database side of a legacy migration: keeping the schema stable while EF6 and EF Core coexist, scaffolding or hand-mapping EF Core, baselining migrations, moving on-premises SQL Server to Azure SQL Database or Managed Instance (DMS, log replay, bacpac), compatibility checks, data migrations, cutover and rollback.

Senior Theory Advanced azure-sql cutover database-migration ef-core ef6 legacy-migration

🎯 Key points

  • Separate the three moves: data-access code (EF6 to EF Core), schema ownership, and hosting (on-prem to Azure SQL); don't do all at once
  • Keep the schema stable while EF6 and EF Core run side by side; one named owner (team and tool) applies migrations, the other ORM is read/write only
  • Map EF Core to the existing schema (scaffold or hand-map), verify by comparing generated SQL and results with EF6 in tests, then baseline with an empty initial migration
  • Choose Azure SQL Database vs Managed Instance by feature needs: cross-database queries, SQL Agent, CLR, Service Broker push you to MI
  • Assess compatibility (Azure Migrate / SQL migration extension) and measure network latency and chattiness from the app servers to Azure before moving
  • Move data with Azure Database Migration Service, MI link / log replay for near-zero downtime, or bacpac for small databases
  • Cutover runbook: freeze writes, final sync, reconcile row counts and checksums, switch connection strings via config, smoke tests, rehearsed rollback
  • Find and involve every consumer of the database (reports, ETL, other teams) and document the plan; batch large data changes with expand/contract

⏱ 30-second answer

I separate three moves that are easy to blur: data-access code (EF6 to EF Core), schema ownership (who runs migrations), and hosting (on-premises SQL Server to Azure SQL). Doing them one at a time keeps each reversible.

During the transition, EF6 and EF Core run against the same, frozen schema; EF Core is mapped to it (scaffolded or by hand) and given an empty baseline migration, and only one tool owns schema changes. For hosting, I assess compatibility, choose Azure SQL Database or Managed Instance (MI if you need SQL Agent, cross-database queries or CLR), and move data with Database Migration Service or log replay for near-zero downtime. The cutover is a rehearsed runbook with a rollback. The trade-off: staging it takes longer, but a combined code-schema-hosting big bang is very hard to debug or undo.

🗣 Full answer (senior)

How I would answer this in an interview

"The first thing I do is pull apart three changes people treat as one. One is data-access code: EF6 to EF Core. Two is schema ownership: which tool generates and applies migrations. Three is hosting: on-prem SQL Server to Azure SQL. Each has its own risks and each should be reversible on its own.

For the code, I keep the schema frozen while EF6 and EF Core both run against it. I map EF Core to the existing tables, either by scaffolding with dotnet ef dbcontext scaffold and cleaning up, or by hand-mapping the entities I've moved, and I check the generated SQL against what EF6 produced. Then I add an empty baseline migration so EF Core thinks the current schema is its starting point. Only one tool is allowed to change the schema at a time; usually EF6 stops issuing migrations the day EF Core takes over. For hosting, I assess the database for Azure compatibility, then pick Azure SQL Database if it's a single, self-contained database, or Managed Instance if it relies on SQL Agent jobs, cross-database queries, CLR or Service Broker. For example, at [company] we [moved a 400 GB database to Managed Instance in Australia East using the MI link and a 20-minute cutover window]; [result].

The mistake I see is doing the hosting move, the ORM change and a schema clean-up in one weekend. When something goes wrong at 2 a.m., you can't tell which change caused it and you can't roll back just one. I'd rather have three boring cutovers than one exciting one."


The three moves

Move What changes Main risks Reversible by
EF6 to EF Core Data-access code Query behaviour, lazy loading, cascade rules, generated SQL Feature flag / route back to EF6 code path
Schema ownership Who generates migrations Drift, duplicate migrations, accidental drops Baseline + review every migration script
On-prem to Azure SQL Hosting, network, auth Compatibility, latency, cutover downtime, logins Reverse replication or keep on-prem read-only

Azure SQL target options

Target Fits Watch out for
Azure SQL Database Single self-contained DB, PaaS simplicity, serverless/hyperscale No SQL Agent, no cross-database queries (without elastic query), no CLR
Azure SQL Managed Instance Lift-and-shift, SQL Agent, cross-DB, CLR, Service Broker, linked servers Higher cost, VNet deployment, longer provisioning
SQL Server on Azure VM Needs OS access or unsupported features You patch and back up

Production example

For a 400 GB claims database, we moved hosting first (to Managed Instance via log replay, 20 minutes of read-only time), ran for a month, then moved data access to EF Core module by module with the schema frozen. Query p95 rose from 18 ms to 26 ms after the move because of network latency from the old app servers, and dropped to 9 ms once the app itself moved to Azure Australia East next to the database.

🔍 What the interviewer is checking

Checks that the candidate can plan the database part of a migration safely, knowing EF6/EF Core coexistence, Azure SQL options, and cutover mechanics.

Green flags

  • Separates code, schema ownership and hosting into distinct steps
  • Knows how to baseline EF Core on an existing schema
  • Chooses Azure SQL Database vs Managed Instance by features
  • Has a rehearsed cutover and rollback, and batches data changes

Red flags

  • Lets both ORMs generate migrations
  • Plans a single weekend that changes everything
  • No mention of compatibility assessment, logins or rollback

📚 Learn in depth

1. Why separate the moves

Big bang                         Staged
------------------------------   ------------------------------
weekend: new host + EF Core +    step 1: hosting (data only)
         schema changes          step 2: EF Core on frozen schema
failure: which one?              step 3: schema evolves under EF Core
rollback: everything             each step has its own rollback

The order varies: moving hosting first proves the network and data path with unchanged code; moving code first lets you test EF Core against the known on-prem database. Either way, one change at a time.

2. EF6 and EF Core on the same schema

They can run side by side in one process (different namespaces: System.Data.Entity vs Microsoft.EntityFrameworkCore) or in different apps during a strangler-fig migration. Rules:

  • The schema doesn't change while both are live, or changes are additive only and made by one owner.
  • EF6's __MigrationHistory table and EF Core's __EFMigrationsHistory are separate; neither knows the other.
  • Concurrency tokens (rowversion) must be mapped in both so neither overwrites the other's changes.
  • Behaviour differences matter: EF Core doesn't lazy-load by default, has different cascade-delete conventions, and throws on untranslatable queries instead of evaluating them on the client.

3. Baselining EF Core migrations

  1. Scaffold or hand-map the model to the current schema.
  2. dotnet ef migrations add Baseline and empty its Up/Down (or keep it full for new environments and insert its history row in existing ones).
  3. Insert the baseline row in __EFMigrationsHistory on existing databases.
  4. From now on, generate idempotent scripts (dotnet ef migrations script --idempotent) and review them before applying.

4. Moving to Azure SQL

Assess: Azure Migrate (with the SQL assessment) or the Azure SQL Migration extension in Azure Data Studio/SSMS reports unsupported features and recommends a target and size. Check compatibility level, collation (Latin1_General_CI_AS vs SQL_Latin1_General_CP1_CI_AS), Windows logins (move to Entra ID authentication and managed identity), and anything that reaches outside the database (linked servers, xp_cmdshell, file paths).

Move data:

Size/downtime          Method
---------------------- -----------------------------------------------
Small, hours OK        bacpac export/import, or backup/restore to MI
Medium, minutes        Azure Database Migration Service (online to MI)
Large, near-zero       MI link (distributed AG) or Log Replay Service to MI;
                       transactional replication to SQL Database

Cutover: stop or freeze writes, let replication catch up, switch connection strings (one config change, not a redeploy), run smoke tests, open traffic. Keep the source read-only for a rollback window.

5. Data migrations

Schema changes that rewrite data (splitting a column, backfilling a new one) follow expand/contract: add the new column, backfill in batches (UPDATE TOP (5000) ... WHERE NewCol IS NULL in a loop), switch reads, then drop the old column in a later release. Never run a multi-hour backfill inside the cutover window or in one transaction (log growth, blocking).

6. Data residency

For Australian personal data, pick Australia East (with Australia Southeast for geo-replication) and record it; the Privacy Act's APP 8 makes you accountable for overseas disclosure, so know where backups and replicas live.

Try it yourself

  1. Scaffold an EF Core context from an existing database and compare a query's SQL with EF6's for the same LINQ.
  2. Create a baseline migration and apply it to a copy of the database without changing the schema.
  3. Export a small database to a bacpac and import it into Azure SQL Database; note unsupported-feature errors.
  4. Write a batched backfill and watch log usage with sys.dm_db_log_space_usage.
  5. Write a one-page cutover runbook with timings, owners and rollback steps, and rehearse it on a copy.

💻 Code

Mapping EF Core to the existing schema that EF6 created (no schema change):

namespace Contoso.Claims.Data;

using Microsoft.EntityFrameworkCore;

public sealed class Claim
{
    public int Id { get; set; }
    public string ClaimNumber { get; set; } = "";
    public decimal Amount { get; set; }
    public int PolicyId { get; set; }
    public byte[] RowVersion { get; set; } = [];
}

public sealed class ClaimsDbContext(DbContextOptions<ClaimsDbContext> options) : DbContext(options)
{
    public DbSet<Claim> Claims => Set<Claim>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Claim>(e =>
        {
            // EF6 pluralised table names and used dbo; match them exactly
            e.ToTable("Claims", "dbo");
            e.Property(c => c.ClaimNumber).HasMaxLength(20).IsRequired();
            e.Property(c => c.Amount).HasColumnType("decimal(18,2)");
            // Same concurrency token as EF6, so neither ORM overwrites the other's writes
            e.Property(c => c.RowVersion).IsRowVersion();
            // EF6 FK naming convention: PolicyId with no cascade from this side
            e.HasIndex(c => c.PolicyId).HasDatabaseName("IX_PolicyId");
        });
    }
}

The baseline migration: EF Core starts from the current schema without trying to recreate it.

namespace Contoso.Claims.Data.Migrations;

using Microsoft.EntityFrameworkCore.Migrations;

public partial class Baseline : Migration
{
    // Intentionally empty: the schema already exists (created by EF6).
    protected override void Up(MigrationBuilder migrationBuilder) { }
    protected override void Down(MigrationBuilder migrationBuilder) { }
}
-- Run once on each existing database so EF Core treats Baseline as applied
IF OBJECT_ID(N'dbo.__EFMigrationsHistory') IS NULL
    CREATE TABLE dbo.__EFMigrationsHistory (
        MigrationId nvarchar(150) NOT NULL PRIMARY KEY,
        ProductVersion nvarchar(32) NOT NULL);

INSERT dbo.__EFMigrationsHistory (MigrationId, ProductVersion)
VALUES (N'20261122000000_Baseline', N'10.0.0');

-- Batched backfill for an expand/contract change: small transactions, no long locks
DECLARE @rows int = 1;
WHILE @rows > 0
BEGIN
    UPDATE TOP (5000) dbo.Claims
    SET    AmountCents = CAST(Amount * 100 AS bigint)
    WHERE  AmountCents IS NULL;
    SET @rows = @@ROWCOUNT;
END

Connection without a password once on Azure SQL (managed identity):

{
  "ConnectionStrings": {
    "Claims": "Server=tcp:contoso-claims.database.windows.net,1433;Database=Claims;Authentication=Active Directory Default;Encrypt=True;"
  }
}

⚠ Common mistakes

  • Mistake: Combining the hosting move, the ORM change and schema clean-up in one cutover. Why it is wrong: when it fails you can't tell which change caused it or roll back just one. Instead: stage the moves, each with its own rollback.
  • Mistake: Letting EF6 and EF Core both generate migrations. Why it is wrong: two histories, drift and conflicting changes. Instead: one owner at a time; freeze EF6 migrations when EF Core takes over.
  • Mistake: Running dotnet ef migrations add Initial against an existing database and applying it. Why it is wrong: it tries to create tables that already exist, or worse, the diff drops and recreates them. Instead: baseline with an empty migration and insert the history row.
  • Mistake: Choosing Azure SQL Database without checking features. Why it is wrong: SQL Agent jobs, cross-database queries and CLR don't exist there, and you discover it at cutover. Instead: run an assessment and choose Managed Instance when those are needed.
  • Mistake: Ignoring collation and logins. Why it is wrong: different default collations break joins with temp tables; Windows logins don't exist in Azure SQL Database. Instead: match collation and move to Entra ID authentication with managed identity.
  • Mistake: Backfilling millions of rows in one transaction during the cutover. Why it is wrong: transaction log growth, blocking and an overrun window. Instead: backfill in batches beforehand with expand/contract.
  • Mistake: No rehearsed rollback. Why it is wrong: a failed cutover turns into an outage. Instead: rehearse the runbook on a production-sized copy, and keep the source read-only and in sync for a rollback window.

🏛 Senior insight: trade-offs

The database is where migrations become irreversible, so I spend proportionally more time here. Two principles: one change per cutover, and the schema is a contract shared by every app that touches it, often reports, ETL and other teams you don't know about yet. I find them with sys.dm_exec_sessions (program and host names), Query Store and login audits, then bring them into the plan: who owns which change, when the freeze is, what the cutover means for them. The runbook, the migration ownership rule and the rollback plan are written down and shared, not held in one person's head.

While EF6 and EF Core coexist, conflicts come from two places: both trying to own the schema (avoid by having one owner and reviewing every migration script), and both writing the same rows (avoid with a shared rowversion concurrency token and by moving a whole aggregate to EF Core at once, not half of it). Before moving hosting, I measure the network: latency from the app servers to the Azure region, and how chatty the app is (calls per request in Application Insights). An app making 200 queries per page over a 15 ms WAN link adds three seconds; fix N+1 queries or move app and database together.

Measure before and after: Query Store top queries and their durations, DTU/vCore usage, wait stats, and end-to-end latency from the app.

Order When it fits Cost When not to
Hosting first Data-centre exit is the driver App-to-DB latency until the app moves App is chatty (N+1) across a WAN
Code (EF Core) first Modernising the app is the driver Two ORMs for a while Schema must change at the same time
Both together Small app, small DB, good tests One risky window Business-critical systems
Leave the DB on-prem Regulatory or latency constraints Hybrid networking App moves to Azure and is chatty

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions baselining EF Core migrations Why: Checks the details of introducing EF Core migrations to an existing database
    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.

  2. When: Candidate mentions EF6 and EF Core behaviour differences Why: Checks which differences bite during the move
    How to 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.

  3. When: Candidate mentions near-zero-downtime database moves to Azure SQL Why: Checks the mechanics of moving a large database with minimal downtime
    How to answer

    Provision the new database from the current migration bundle, then copy the tenant's rows table by table in foreign-key order (SqlBulkCopy or BCP, keeping key values), and verify with counts and checksums. Track changes made during the copy (a ModifiedAt watermark, change tracking or CDC), then take a short write freeze for that tenant, apply the final delta, flip the catalogue entry to the new connection and clear the catalogue cache. Keep the source rows read-only for a rollback window, then delete them. Rehearse on a copy and measure the freeze time first.

🛠 Real-world problems: how you handle them

Cutover rehearsal finds a collation mismatch that breaks temp-table joins
Situation
A [claims] system: .NET Framework app with EF6 on an on-prem SQL Server 2016, [about 400 GB], moving to Azure SQL Managed Instance in [Australia East] ahead of a data-centre exit.
Signals
During the cutover rehearsal on a restored copy, [nightly reports] failed with 'Cannot resolve the collation conflict between SQL_Latin1_General_CP1_CI_AS and Latin1_General_CI_AS'. Some stored procedures failed the same way.
Investigation
Compared server and database collations: the database (restored from on-prem) used `SQL_Latin1_General_CP1_CI_AS`, but the new Managed Instance had been created with `Latin1_General_CI_AS`, so `tempdb` used a different collation from the user database. Found stored procedures creating temp tables without `COLLATE DATABASE_DEFAULT` and joining them to user tables.
Resolution
Immediate: recreated the Managed Instance with the matching server collation (an instance's collation can't be changed after creation). Real fix: added `COLLATE DATABASE_DEFAULT` to temp table definitions so the code no longer depends on server collation.
Prevention
Assessment checklist now includes server and database collation; the rehearsal runs the full nightly report suite; the target instance is defined in Bicep with the collation explicit.

How to tell it (STAR)

**S:** We were moving [a 400 GB claims database] from on-prem SQL Server to Managed Instance before a data-centre exit. **T:** I owned the cutover plan and insisted on a full rehearsal on a production-sized copy. **A:** The rehearsal broke the nightly reports with collation conflicts. I traced it to the new instance having a different server collation from the database, which affects temp tables. Since that can't be changed after creation, we rebuilt the instance with the right collation, fixed the stored procedures to use `COLLATE DATABASE_DEFAULT`, and made collation explicit in our Bicep. **R:** The real cutover took [22 minutes] of read-only time with zero failed reports, and the rehearsal step is now mandatory for every database move.

More in Migration Topics

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me