loading experience

.NET

What's new in EF Core 11: complex types, vectors, Cosmos

EF Core 11 on .NET 11: complex types, FullJoin, VECTOR_SEARCH, full-text, JSON_CONTAINS, Cosmos DB, SQLite and new dotnet ef commands.

EF Core 11 brings news in almost every area: more mature complex types, better LINQ and SQL, many SQL Server features (vector search, full-text, JSON), improvements for SQLite and Azure Cosmos DB, and new migration tooling. Below is one section per feature, with code from the official documentation.

How to upgrade

  • EF Core 11 requires the .NET 11 SDK to build and the .NET 11 runtime to run.
  • It does not run on earlier .NET versions or on .NET Framework.

Download .NET 11 from the official page.

Complex types

Complex types and JSON columns with TPT/TPC inheritance

Until now, complex types and JSON columns could not be used on entities with TPT (table-per-type) or TPC (table-per-concrete-type) inheritance. EF 11 supports them: for an Animal entity with AnimalDetails as a complex type, EF creates the Details_BirthDate and Details_Veterinarian columns on the Animal table, or maps the property to a JSON column.

modelBuilder.Entity<Animal>().UseTptMappingStrategy();

modelBuilder.Entity<Animal>()
    .UseTptMappingStrategy()
    .ComplexProperty(a => a.Details, b => b.ToJson());

Configuring via lambda chaining

You no longer need to go through ComplexProperty to configure a complex type property: just chain member access in the lambda passed to Property.

modelBuilder.Entity<MyEntity>()
    .Property(e => e.Details.Description)
    .HasMaxLength(500);

Keys and indexes on complex type properties

Keys and indexes can use scalar properties nested inside non-collection complex types, also by name ("Address.PostalCode"). For relational providers, indexes can also target paths inside complex types mapped to JSON columns; in complex collections, [] means all elements and a numeric indexer a specific one.

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

modelBuilder.Entity<Order>()
    .ComplexCollection(o => o.Items, b => b.ToJson());
modelBuilder.Entity<Order>()
    .HasIndex("Items[].Sku");

Stabilization

Significant effort went into stabilizing complex types so they can be an alternative to owned entities. Fixed bugs include queries on complex types whose container is mapped to a table and a view, ComplexProperty with TPT, comparison of nested complex types, assignment in ExecuteUpdate, and ReloadAsync with a null nullable complex property. Complex types are also supported in Azure Cosmos DB (see below).

LINQ and SQL translation

Better SQL for to-one joins

With split queries (AsSplitQuery()) EF no longer adds unnecessary joins to reference navigations, and no longer adds redundant keys from reference navigations to ORDER BY. The documentation reports a 29% improvement in a common split query scenario and 22% in a single query scenario; actual performance depends on your schema and data.

GroupBy enhancements

Translation and materialization of GroupBy queries improve: you can compose navigation access and joins over a per-group top result, aggregates over reference navigations use joins before grouping instead of correlated subqueries, and left-joined non-entity projections (anonymous types, DTOs) are materialized correctly.

FullJoin

.NET 11 adds the LINQ FullJoin operator, which EF Core 11 translates to FULL JOIN on relational databases.

var results = await context.Customers
    .FullJoin(
        context.Orders,
        c => c.Id,
        o => o.CustomerId,
        (c, o) => new { Customer = c, Order = o })
    .ToListAsync();

Stripping of no-op CASTs

EF no longer generates CAST expressions that convert a column to the type it already has (common with value-converted properties): they are stripped during SQL post-processing, so the database can use indexes on the column.

MaxBy and MinBy

MaxBy/MinBy (and the async versions) are now translated, returning the element with the maximum or minimum key value. The example finds the blog with the most posts and produces SELECT TOP(1) ... ORDER BY (SELECT COUNT(*) ...) DESC.

var blogWithMostPosts = await context.Blogs.MaxByAsync(b => b.Posts.Count());

SQL Server

JsonPathExists

EF.Functions.JsonPathExists() checks whether a JSON path exists in a JSON document and translates to JSON_PATH_EXISTS (available since SQL Server 2022). It works with scalar string properties, complex types and owned entities mapped to JSON.

var blogs = await context.Blogs
    .Where(b => EF.Functions.JsonPathExists(b.JsonData, "$.OptionalInt"))
    .ToListAsync();

VECTOR_SEARCH() and vector indexes

This is experimental in SQL Server and subject to change, including the EF Core APIs. After EF Core 10's VectorDistance() (exact distance), EF 11 creates vector indexes through migrations and offers VectorSearch() for approximate (ANN) search on SQL Server 2025; without WithApproximate() the search is exact (kNN). The result is VectorSearchResult<TEntity>, with the entity and the distance.

modelBuilder.Entity<Blog>()
    .HasVectorIndex(b => b.Embedding, "cosine");

var blogs = await context.Blogs
    .VectorSearch(b => b.Embedding, embedding, "cosine")
    .OrderBy(r => r.Distance)
    .Take(5)
    .WithApproximate()
    .ToListAsync();

Vector properties not loaded by default

SqlVector<T> columns are no longer included in the SELECT when materializing entities; they remain usable in WHERE and ORDER BY and are loaded with an explicit projection. A minimal benchmark showed an almost 9x improvement against a local database and about 22x against a remote Azure SQL database; real results vary.

Full-text: catalog, index and table-valued functions

Full-text catalogs and indexes are configured in the model and created by migrations (previously you had to add SQL by hand). FreeTextTable and ContainsTable translate FREETEXTTABLE() and CONTAINSTABLE() and return FullTextSearchResult<TEntity>, with the entity and the ranking score (ContainsTable works the same way).

modelBuilder.HasFullTextCatalog("ftCatalog");
modelBuilder.Entity<Blog>()
    .HasFullTextIndex(b => b.FullName)
    .UseKeyIndex("PK_Blogs")
    .UseCatalog("ftCatalog");

var results = await context.Blogs
    .FreeTextTable("John", b => b.FullName)
    .Select(r => new { Blog = r.Value, Rank = r.Rank })
    .OrderByDescending(r => r.Rank)
    .ToListAsync();

Hybrid search

Vector search and full-text table-valued functions can be combined into hybrid search: full-text finds exact linguistic matches, vector search finds semantically similar ones, and the two rankings are merged. FullJoin support makes the pattern more complete; the documentation shows an example that merges the rankings with an RRF score.

JSON_CONTAINS

With SQL Server 2025 (compatibility level 170), Contains queries over primitive collections stored as JSON use JSON_CONTAINS instead of the OPENJSON-based translation, and can use a JSON index. The translation applies only when EF knows that at least one side is non-nullable, because JSON_CONTAINS doesn't search for null values; otherwise it falls back to OPENJSON. For direct use (path, search mode) there is EF.Functions.JsonContains().

optionsBuilder
    .UseSqlServer("<CONNECTION STRING>", o => o.UseCompatibilityLevel(170));

var blogs = await context.Blogs
    .Where(b => EF.Functions.JsonContains(b.JsonData, 8, "$.Rating") == 1)
    .ToListAsync();

JSON indexes

EF Core 11 creates and scaffolds JSON indexes for paths inside complex types mapped to JSON columns, generating CREATE JSON INDEX.

modelBuilder.Entity<Customer>()
    .ComplexProperty(c => c.Contact, b => b.ToJson().HasColumnType("json"));
modelBuilder.Entity<Customer>()
    .HasIndex("Contact.Address.City");

Temporal period properties mapped to CLR properties

The PeriodStart/PeriodEnd properties of temporal tables no longer have to be shadow properties: map them to regular CLR properties with the lambda overloads of HasPeriodStart/HasPeriodEnd and use them directly in queries, without EF.Property. They stay ValueGenerated.OnAddOrUpdate, generated by SQL Server.

modelBuilder
    .Entity<Employee>()
    .ToTable(
        "Employees",
        b => b.IsTemporal(
            b =>
            {
                b.HasPeriodStart(e => e.PeriodStart);
                b.HasPeriodEnd(e => e.PeriodEnd);
            }));

Date/time translations

For DateTimeOffset, the properties DateTime, UtcDateTime, LocalDateTime and Offset.TotalMinutes, the ToOffset method (SWITCHOFFSET) and the constructors from DateTime (TODATETIMEOFFSET) are translated. EF.Functions.DateTrunc() truncates DateTime, DateTimeOffset, DateOnly and TimeOnly to a given precision (DATETRUNC).

Other changes

UseSqlServer now defaults to compatibility level 160 (SQL Server 2022), enabling translations such as LEAST and GREATEST; a breaking change note covers it.

SQLite

With string.Join and string.Concat over a grouping, you can now order with OrderBy/OrderByDescending inside the aggregate: the translation uses group_concat with ORDER BY (requires SQLite 3.44.0 or later; previously such queries fell back to client evaluation). Microsoft.Data.Sqlite can also bind UInt128 parameters, stored as a zero-padded 39-digit text; reading UInt128 from data readers is not yet supported.

var blogs = await context.Blogs
    .Select(b => new
    {
        b.Name,
        Posts = string.Join(
            ", ",
            b.Posts.OrderByDescending(p => p.Id).Select(p => p.Title))
    })
    .ToListAsync();

Azure Cosmos DB

  • Complex types: fully supported, embedded as nested JSON objects (or arrays for collections), with queries, inserts and updates. They have value semantics and no identity, so they often fit better than owned types.
  • Indexes and indexing policy: you can disable automatic indexing, exclude paths, and define single-property, composite, vector and full-text indexes, including through complex types and complex collections.
  • Transactional batches: used by default (AutoTransactionBehavior: Auto, Never for the pre-11 behavior, Always which requires a single batch).
  • Bulk execution: enabled with BulkExecutionEnabled() to improve throughput when saving many entities.
  • Session tokens: managed manually with SessionTokenManagementMode, useful with multiple instances and round-robin load balancing.
  • Modernized JSON serializer: the provider uses System.Text.Json instead of Newtonsoft.Json; the __jObject shadow property is removed and unmapped JSON properties are no longer preserved on round-trip (breaking change).
  • Undefined values in projections: now always throw InvalidOperationException; use IsDefined or CoalesceUndefined.
modelBuilder.Entity<Order>(b =>
{
    b.HasAutomaticIndexing()
        .Except("/InternalNotes/?");
    b.HasIndex(o => new { o.CustomerId, o.OrderDate });
});
options => options.SessionTokenManagementMode(SessionTokenManagementMode.SemiAutomatic)

var sessionToken = context.Database.GetSessionToken();
context.Database.UseSessionToken(sessionToken);
var results = await context.Entities
    .Where(x => EF.Functions.IsDefined(x.Associate!.NestedAssociate!.Id))
    .Select(x => new { x.Associate!.NestedAssociate!.Id })
    .ToListAsync();

Migrations and tooling

  • Excluding foreign keys from migrations: the relationship stays in the EF model (queries, change tracking) but the constraint isn't created; the index on the column remains. Useful for legacy databases or data synchronization.
  • Latest migration ID in the model snapshot: if two developers create migrations on divergent branches, merging produces a conflict that flags the divergence.
  • Create and apply in one step: dotnet ef database update --add (-Add in PowerShell) scaffolds the migration, compiles it with Roslyn and applies it, useful for .NET Aspire and containers; the files are still saved to disk.
  • Connection and offline: migrations remove and database drop accept --connection; migrations remove --offline skips the database connection (can't be combined with --force).
  • Configuration file: .config/dotnet-ef.json provides default values (project, startup project, framework, context...); command-line options take precedence.
  • -NoBuild for Add-Migration and Update-Database in the Package Manager Console.
  • Wildcard context: --context "*" for migrations list, migrations script, database update and database drop.
  • The tool writes logging and status to standard error, reserving standard output for the actual result; an analyzer warns when ToAsyncEnumerable is used instead of AsAsyncEnumerable.
modelBuilder.Entity<Blog>()
    .HasMany(e => e.Posts)
    .WithOne(e => e.Blog)
    .HasForeignKey(e => e.BlogId)
    .ExcludeForeignKeyFromMigrations();
dotnet ef database update InitialCreate --add
dotnet ef migrations remove --offline
dotnet ef migrations list --context "*"
{
  "project": "src/App.Infrastructure",
  "startupProject": "src/App.Api",
  "framework": "net11.0",
  "context": "AppDbContext"
}

Sources

Comments (0)

No comments yet.

Leave a comment