Entity Framework 6 to EF Core on an Existing Database: A Worked Example

Entity Framework 6 still works and still gets security fixes, but it gets no new features, and everything new in .NET data access happens in EF Core. Sooner or later a long-lived .NET application makes the move. The database stays: it is full of data, and other systems read it. So the real task is to make EF Core work with tables that Entity Framework 6 designed, and to prove that the application behaves the same afterwards.

This case does that for a small order desk. The code is on GitHub: chudovo/application-modernization, case 05. It is the step that follows moving the application from .NET Framework to .NET 10.

At a glance

BeforeAfter
LibraryEntity Framework 6.5EF Core 10
DatabaseSQL Server, created by EF6 Code Firstthe same database, unchanged
Mappingconventions and a few attributeswritten out to match the existing tables
Related datalazy loading through virtual propertiesInclude or a projection per query
Raw SQLSqlQuery with SqlParameterSqlQuery with an interpolated string
Migration history__MigrationHistory__EFMigrationsHistory, starting with an empty baseline
Shared scenarios passing17 of 1717 of 17

Two steps, not one

Entity Framework 6 has run on modern .NET since version 6.3. That means the runtime and the data access library do not have to change in the same release. The old data layer in this case is Entity Framework 6.5 running on .NET 10, on Linux, against SQL Server in a container. If you are still on .NET Framework, move the runtime first and keep EF6; then replace EF6 as a separate change with its own tests.

The existing database

The schema in the repository is not written by hand. It is the script that Entity Framework 6 Code First Migrations generates for the old model, and the build regenerates it to check that it has not drifted. It shows what EF6 decided by convention:

-- Generated by Entity Framework 6 Code First Migrations for the old model
CREATE TABLE [dbo].[Orders] (
    [Id] [int] NOT NULL IDENTITY,
    [CreatedUtc] [datetime] NOT NULL,
    [Total] [decimal](18, 2) NOT NULL,
    [RowVersion] rowversion NOT NULL,
    [Customer_Id] [int] NOT NULL,
    CONSTRAINT [PK_dbo.Orders] PRIMARY KEY ([Id])
)
CREATE TABLE [dbo].[TagOrders] (
    [Tag_Id] [int] NOT NULL,
    [Order_Id] [int] NOT NULL,
    CONSTRAINT [PK_dbo.TagOrders] PRIMARY KEY ([Tag_Id], [Order_Id])
)
CREATE INDEX [IX_Customer_Id] ON [dbo].[Orders]([Customer_Id])

Three of these decisions matter later: the foreign key column is called Customer_Id, the many-to-many join table is called TagOrders, and dates are stored as datetime.

Step 1: scenarios that run against both versions

All data access of the application sits behind one class, OrderStore, with the same public methods in both versions. That lets one source file of 17 scenarios compile against the EF6 data layer and against the EF Core one. Every test gets a fresh database with the EF6 schema and rows as the old application wrote them, on a real SQL Server:

[Fact]
public void New_order_is_stored_with_lines_total_and_tags()
{
    var id = _store.PlaceOrder(new NewOrder(2, Noon,
        [Line("LAMP-07", 3, 39.99m), Line("SHELF-03", 1, 120.00m)], "priority", "export"));

    var order = _store.GetOrder(id);
    Assert.Equal("Atelier Dubois", order.CustomerName);
    Assert.Equal(239.97m, order.Total);
    Assert.Equal(["export", "priority"], order.Tags);

    // The existing tag is reused, the new one is created once.
    Assert.Equal(["export", "priority", "wholesale"], _database.Rows("SELECT Name FROM dbo.Tags ORDER BY Name"));
}

The scenarios cover reading existing orders and customers, new orders with lines and tags, the many-to-many relation, optimistic concurrency with a row version, cascading deletes, a grouped report, hand-written SQL, paging, and an import that must be all or nothing.

Step 2: tell EF Core what EF6 decided

EF Core has conventions too, and they are different. Everything EF6 chose silently has to be written down so that the model matches the tables that exist:

model.Entity<Order>(order =>
{
    order.HasKey(o => o.Id).HasName("PK_dbo.Orders");

    // EF6 mapped DateTime to datetime. EF Core would assume datetime2.
    order.Property(o => o.CreatedUtc).HasColumnType("datetime");

    // The class has no foreign key property. EF6 named the column Customer_Id, EF Core would look for CustomerId.
    order.HasOne(o => o.Customer).WithMany(c => c.Orders)
        .HasForeignKey("Customer_Id").IsRequired()
        .HasConstraintName("FK_dbo.Orders_dbo.Customers_Customer_Id");
    order.HasIndex("Customer_Id").HasDatabaseName("IX_Customer_Id");

    // The join table: EF6 called it TagOrders, EF Core would look for OrderTag with OrdersId and TagsId.
    order.HasMany(o => o.Tags).WithMany(t => t.Orders).UsingEntity<Dictionary<string, object>>(
        "TagOrders",
        right => right.HasOne<Tag>().WithMany().HasForeignKey("Tag_Id"),
        left => left.HasOne<Order>().WithMany().HasForeignKey("Order_Id"),
        join => join.HasKey("Tag_Id", "Order_Id").HasName("PK_dbo.TagOrders"));
});

To see how much this matters, each part was removed from the finished EF Core version and the tests were run again:

Removed from the EF Core versionResult
All relationship and table mapping (EF Core conventions only)14 of 17 scenarios fail: Invalid column name ‘CustomerId’, Invalid object name ‘OrderTag’
Include in the method that reads an order6 of 17 scenarios fail with NullReferenceException
The decimal conversion1 scenario fails: 19.999 is stored as 20.00 instead of 19.99
The datetime column typeall 17 scenarios pass, the schema checks fail
Key, index and constraint namesall 17 scenarios pass, the schema checks fail

Lazy loading is gone

EF6 code often reads one entity and walks to its relatives. Each step is a hidden query. In EF Core the navigation property is simply null:

// Entity Framework 6: Customer, Lines and Tags load on first access, one query each.
var order = db.Orders.Find(id);
return new OrderDetails { CustomerName = order.Customer.Name, /* ... */ };

// EF Core: the same line throws NullReferenceException. The query has to name what it needs.
var order = db.Orders
    .Include(o => o.Customer).Include(o => o.Lines).Include(o => o.Tags)
    .AsSplitQuery().AsNoTracking()
    .SingleOrDefault(o => o.Id == id) ?? throw new NotFoundException("Order " + id);

EF Core has a package that brings lazy loading back. Using it to avoid this work keeps the hidden queries, which are usually the reason the data layer is slow. Going through every read once is the more useful investment.

Decimals are rounded, not cut off

This one produces no error in either version. A price with three decimals written to a column with two: Entity Framework 6 stores 19.999 as 19.99, EF Core stores 20.00. One scenario caught it. A library upgrade must not change money, so the new version keeps the old behaviour explicitly:

// 19.999 written to a decimal(18,2) column: EF6 stored 19.99, EF Core stores 20.00.
// Money must not change during a library upgrade, so the old behaviour is kept, in one place.
private static readonly ValueConverter<decimal, decimal> AsEf6Stored =
    new(value => decimal.Round(value, 2, MidpointRounding.ToZero), value => value);

line.Property(l => l.UnitPrice).HasPrecision(18, 2).HasConversion(AsEf6Stored);

Whether cutting off is what the business actually wants is a fair question. It should be answered on purpose, not by a package update.

The differences that no scenario catches

The last two rows of the table above are the dangerous ones. With dates left as EF Core’s default datetime2, or with EF Core’s default names for keys and indexes, every scenario passes. The application works. The problem appears weeks later, in the first real migration, which tries to alter columns and to rename or drop objects that do not exist under those names.

So the case has a second kind of test. It reads the catalog of the existing database, builds the same description from the EF Core model, and compares them line by line: every column with type and nullability, every key, foreign key and index with its name.

Migrations: start with an empty baseline

The tables exist, so the first EF Core migration must not create them. The tooling generates a migration full of CREATE TABLE statements; its body is deleted. Applying it only records one row in the new history table. The model snapshot generated next to it describes the existing database, and every later migration is a difference from that. A test proves the baseline changes nothing:

[Fact]
public void The_baseline_migration_changes_no_table_and_is_recorded()
{
    var before = Database(line => !IsHistoryTable(line));   // every column, key, foreign key and index, one per line
    using var db = OrderDeskContext.Open(_database.ConnectionString);

    db.Database.Migrate();

    Assert.Equal(before, Database(line => !IsHistoryTable(line)));
    Assert.False(db.Database.HasPendingModelChanges());
}

The old history table of EF6 is left in place. It costs nothing, and it is the record of how the schema came to be.

One difference in the other direction

One existing order was created at 09:15:00.123. Looking it up by exactly that time finds nothing with EF6 and finds it with EF Core. EF6 sends the value as datetime2, and SQL Server converts the stored datetime to 09:15:00.1233333 before comparing. EF Core, with the column mapped as datetime, compares exactly. The upgrade fixes a lookup that silently never worked. That is still a change in behaviour, so it is recorded as one test per version and not hidden.

What is verified, and what is not

CheckResult
17 scenarios against Entity Framework 6, SQL Server 202217 / 17
17 scenarios against EF Core 10, SQL Server 202217 / 17
EF Core model equals the existing schema, including namesequal
Baseline migration changes no table, existing data readable afterwardspasses
Committed schema script equals what EF6 generatesequal
  • Performance was not measured. The number of round trips changes, the effect on a real workload was not compared.
  • Old and new were not run side by side. In a rollout both versions often write to the same database for a while. The schema is untouched, so this should work, but no test runs them concurrently.
  • SQL Server only, Code First only. No EDMX model, no stored procedure mapping, no table-per-type inheritance, no spatial types. Each has its own migration story.
  • The API stays synchronous in both versions, as in the original.

One thing went wrong in the test setup: the connection string builder of the new SQL client writes the option as Trust Server Certificate, with spaces, and the old client rejects that with Keyword not supported. If both versions read the same configuration during a rollout, keep the spelling without spaces.

Run it yourself

You need the .NET 10 SDK and Docker for SQL Server. The tests create and drop their own databases:

docker run -d -e ACCEPT_EULA=Y -e MSSQL_SA_PASSWORD=Local_dev_only_1 -p 14330:1433 mcr.microsoft.com/mssql/server:2022-latest
dotnet test before/tests/OrderDesk.Scenarios
dotnet test after/tests/OrderDesk.Scenarios

When this path fits

Replacing the data access library under a working application is a contained change: no new features, no new schema, and a clear definition of done. It fits once the application runs on modern .NET and the team wants what EF Core offers, from better SQL to compiled models and bulk updates. If the database itself is the problem, that is a different project. How the pieces of such a programme fit together is covered in the application modernization strategy guide and the legacy database modernization guide.

If you need a team for a migration like this, see our comparison of top .NET modernization companies.

Eugene started his career at Chudovo in 2015. The expert is responsible for advisory services that include but are not limited to close communication with the clients, analyzing their needs, designing tailored software strategies, etc. Throughout the practice at Chudovo, an IT consultant took part in over 17 projects, covering a wide range of client services and solving customer pains from the business perspective. With Eugene’s involvement, the customers were able to build an efficient strategy for business growth as well as to set up a long-term technology roadmap. Eugene takes an active part in software development projects in the role of IT consultant and composes proposals for the customers.