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.
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.
"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 scaffoldand 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."
| 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 |
| 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 |
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.
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
Red flags
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.
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:
__MigrationHistory table and EF Core's __EFMigrationsHistory are separate; neither knows the other.rowversion) must be mapped in both so neither overwrites the other's changes.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).__EFMigrationsHistory on existing databases.dotnet ef migrations script --idempotent) and review them before applying.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.
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).
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.
sys.dm_db_log_space_usage.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;"
}
}
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.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 |
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.
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.
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.
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.
Last updated 23 Nov 2026.