# Peek into ASP.NET Core 11 and EF Core 11

> ASP.NET Core 11 adds SignalR token refresh, union types in Minimal APIs and OpenAPI 3.2. EF Core 11 brings vector search, full-text search and FullJoin.

- Author: Pavle Davitkovic
- Published: 2026-11-25
- Topic: .NET
- Canonical: https://pavle.codes/blog/aspnet-core-11-ef-core-11/

ASP.NET Core 11 adds SignalR token refresh, async validation and OpenAPI 3.2, while EF Core 11 brings vector, full-text and hybrid search to SQL Server. This is the follow-up I promised in the [C# 15 and .NET 11 post](https://pavle.codes/blog/net-11/).

Both got a long list of improvements in .NET 11 (see the full [ASP.NET Core 11](https://learn.microsoft.com/en-us/aspnet/core/release-notes/aspnetcore-11) and [EF Core 11](https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-11.0/whatsnew) release notes). Below are the features I'd reach for first.

## ASP.NET Core

### SignalR

#### Authentication refresh

SignalR connections are long-lived, and access tokens usually aren't. Until now, you had two options when a bearer token expired mid-connection:

1. **Keep the connection open.** By default, a WebSocket connection keeps working with the identity it started with, even after the token expires.
2. **Close it.** With `CloseOnAuthenticationExpiration`, the server drops the connection at expiry, and the client has to reconnect with a new token.

```mermaid
sequenceDiagram
    accTitle: What happens to a SignalR connection when its token expires
    accDescr: The client connects with a token valid for 60 minutes. When the token expires, either the server keeps the connection open with the expired identity, or, with CloseOnAuthenticationExpiration, closes it and the client must get a new token and reconnect.
    participant C as Client
    participant S as Server
    C->>S: Connect with token (valid 60 min)
    S-->>C: Connected
    Note over C,S: 60 minutes later, the token expires
    alt Default
        C->>S: Invoke hub method
        S-->>C: Runs with the expired identity
    else CloseOnAuthenticationExpiration
        S--xC: Connection closed
        C->>S: Get a new token and reconnect
        S-->>C: New connection
    end
```

ASP.NET Core 11 adds [authentication refresh](https://learn.microsoft.com/en-us/aspnet/core/signalr/authn-and-authz#authentication-refresh), which updates the credentials of an active connection without reconnecting. You enable it per hub:

```csharp
app.MapHub<ChatHub>("/chat", options =>
{
    options.EnableAuthenticationRefresh = true;
    options.CloseOnAuthenticationExpiration = true;

    // Optional: reject a refresh the built-in check would accept
    options.OnAuthenticationRefresh = context =>
        Task.FromResult(context.NewUser.HasClaim("tenant", "contoso"));
});
```

This maps a `/chat/refresh` endpoint next to `/chat/negotiate`. The server accepts a new token only when it belongs to the same user, comparing the first `sub`, `NameIdentifier` or `Upn` claim. `OnAuthenticationRefresh` can add your own rules, but it can only reject a refresh, never approve one that fails the built-in check.

On the client, `WithAuthenticationRefresh` asks the `AccessTokenProvider` for a new token before the current one expires:

```csharp
await using var connection = new HubConnectionBuilder()
    .WithUrl("https://localhost:5001/chat", options =>
    {
        options.AccessTokenProvider = GetAccessTokenAsync;
    })
    .WithAuthenticationRefresh(options =>
    {
        // Defaults to five minutes
        options.RefreshBeforeExpiration = TimeSpan.FromSeconds(10);
    })
    .Build();

connection.AuthenticationRefreshed += context =>
{
    Console.WriteLine($"Refreshed. New lifetime: {context.NewTokenLifetime}");
    return Task.CompletedTask;
};

connection.AuthenticationRefreshFailed += context =>
{
    Console.WriteLine($"Refresh failed: {context.Exception?.Message}");
    return Task.CompletedTask;
};

await connection.StartAsync();
```

With a 20-second token, the connection stayed open well past the original expiry, refreshing about every 10 seconds:

```text
Connected: pavle, exp 1795465398
Refreshed. New lifetime: 00:00:19
Refreshed. New lifetime: 00:00:19
Refreshed. New lifetime: 00:00:19
State after 35s: Connected
```

When `OnAuthenticationRefresh` rejects the new token, the client gets a 403. A failed refresh doesn't close the connection and isn't retried, so `CloseOnAuthenticationExpiration` closes it when the old token runs out:

```text
Refresh failed: Response status code does not indicate success: 403 (Forbidden).
Closed:
State after 35s: Disconnected
```

The hub can react to a refresh by overriding `OnAuthenticationRefreshedAsync`:

```csharp
[Authorize]
public class ChatHub : Hub
{
    public override Task OnAuthenticationRefreshedAsync()
    {
        // Context.User now holds the refreshed identity
        return Clients.Caller.SendAsync("AuthenticationRefreshed", Context.UserIdentifier);
    }
}
```

> [!NOTE]
> A hub method that's already running keeps the `Context.User` it started with. Only later invocations see the refreshed user.

You can also refresh on demand, for example right after the user's roles change, with `RefreshAuthenticationAsync()`. The TypeScript client supports the same flow through `withAuthenticationRefresh` and `refreshAuthentication()`, and Blazor Server circuits enable it automatically.

#### Cancel hub invocations

Until now, a client could cancel only **streaming** hub invocations. A regular `InvokeAsync` call ran to completion on the server, even when the client had stopped waiting for it.

In ASP.NET Core 11, [canceling a regular invocation](https://learn.microsoft.com/en-us/aspnet/core/release-notes/aspnetcore-11#cancel-hub-invocations-from-the-client) also cancels it on the server. Add a `CancellationToken` parameter to the hub method:

```csharp
public class ChatHub : Hub
{
    public async Task<string> GenerateReport(CancellationToken cancellationToken)
    {
        await Task.Delay(TimeSpan.FromMinutes(5), cancellationToken);
        return "Report ready";
    }
}
```

And pass a token to `InvokeAsync` on the client:

```csharp
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(2));

try
{
    string report = await connection.InvokeAsync<string>("GenerateReport", cts.Token);
}
catch (OperationCanceledException)
{
    Console.WriteLine("Report canceled after 2 seconds");
}
```

When the token is canceled, the client sends a cancellation message, and the server triggers the hub method's `CancellationToken`. The server log shows the report stopping two seconds in, instead of holding a hub invocation for five minutes:

```text
info: ChatHub[0]
      Report started
info: ChatHub[0]
      Report canceled by the client
```

There's nothing to configure on the server. The `CancellationToken` parameter isn't sent by the client; SignalR fills it in, the same way it does for streaming methods.

### Minimal APIs

#### Endpoint filters observe binding failures

When a parameter fails to bind, such as `?page=abc` for an `int page`, Minimal APIs return a 400 with an empty body:

```text
HTTP/1.1 400 Bad Request
Content-Length: 0
```

In ASP.NET Core 11, [the filter pipeline runs even when binding fails](https://learn.microsoft.com/en-us/aspnet/core/release-notes/aspnetcore-11#endpoint-filters-observe-parameter-binding-failures). An [endpoint filter](https://pavle.codes/blog/filters-in-net/#endpoint-filter) can check for the 400 status code and return its own response:

```csharp
app.MapGet("/orders/{id:int}", (int id, int page) => Results.Ok(new { id, page }))
    .AddEndpointFilter(async (context, next) =>
    {
        if (context.HttpContext.Response.StatusCode == StatusCodes.Status400BadRequest)
        {
            return TypedResults.Problem(
                title: "Invalid request",
                detail: "Query parameter 'page' must be a whole number.",
                statusCode: StatusCodes.Status400BadRequest);
        }

        return await next(context);
    });
```

`GET /orders/5?page=abc` now returns a [problem details](https://pavle.codes/blog/problem-details-dotnet/) response:

```json
{
  "type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
  "title": "Invalid request",
  "status": 400,
  "detail": "Query parameter 'page' must be a whole number."
}
```

In production, this works out of the box. In the `Development` environment, `ThrowOnBadRequest` defaults to `true`, so binding failures throw `BadHttpRequestException` to the developer exception page and the filter never sees the 400. Set it to `false` to get the same behavior locally:

```csharp
builder.Services.Configure<RouteHandlerOptions>(options => options.ThrowOnBadRequest = false);
```

#### C# union types

I covered [union types](https://pavle.codes/blog/net-11/#union-types) and their `System.Text.Json` support in the previous post. ASP.NET Core 11 [supports them](https://learn.microsoft.com/en-us/aspnet/core/release-notes/aspnetcore-11#c-union-types) everywhere it uses `System.Text.Json`: request and response bodies in Minimal APIs and MVC, SignalR's JSON hub protocol, and Blazor.

A union can be returned directly from an endpoint:

```csharp
public union Result<T>(Success<T>, ApiError);

app.MapGet("/users/{id:int}", (int id) => UserService.GetById(id));
```

The response holds whichever case the union contains:

```json
{"value":{"id":1,"name":"Pavle"}}
{"message":"User 999 was not found."}
```

It also binds from a request body. When the cases are both JSON objects, the structural classifier picks the case by its property names:

```csharp
public sealed record Email(string To, string Subject);
public sealed record Sms(string PhoneNumber, string Text);

[JsonUnion(TypeClassifier = typeof(JsonUnionTypeStructuralClassifier))]
public union Notification(Email, Sms);

app.MapPost("/notifications", (Notification notification) => notification switch
{
    Email email => Results.Ok($"Email sent to {email.To}"),
    Sms sms => Results.Ok($"SMS sent to {sms.PhoneNumber}"),
    null => Results.BadRequest(),
});
```

Posting `{"phoneNumber":"+15555550100","text":"Hi"}` returns `"SMS sent to +15555550100"`.

> [!NOTE]
> Unions bind only from the body. Route values, query strings, headers and form fields don't support them.

#### Async validation

[Minimal API validation](https://pavle.codes/blog/net-10/#minimal-apis-get-built-in-validation) in .NET 10 supported only synchronous rules. ASP.NET Core 11 adds [async validation](https://learn.microsoft.com/en-us/aspnet/core/release-notes/aspnetcore-11#async-validation-for-minimal-apis) through two new `DataAnnotations` APIs: `AsyncValidationAttribute` and `IAsyncValidatableObject`.

For a single property, derive from `AsyncValidationAttribute` and implement `IsValidAsync`:

```csharp
public sealed class UniqueEmailAttribute : AsyncValidationAttribute
{
    // The synchronous IsValid is abstract too. Throw so it's never used by mistake.
    protected override ValidationResult? IsValid(object? value, ValidationContext context) =>
        throw new InvalidOperationException("Validate this attribute with IsValidAsync.");

    protected override async Task<ValidationResult?> IsValidAsync(
        object? value, ValidationContext context, CancellationToken cancellationToken)
    {
        var users = context.GetRequiredService<IUserService>();

        if (value is string email && await users.EmailExistsAsync(email, cancellationToken))
        {
            return new ValidationResult("That email is already registered.");
        }

        return ValidationResult.Success;
    }
}
```

And apply it like any built-in attribute:

```csharp
public sealed record RegisterUser(
    [property: Required, EmailAddress, UniqueEmail] string Email,
    [property: Required, MinLength(8)] string Password);

builder.Services.AddValidation();

app.MapPost("/users", (RegisterUser request) =>
    Results.Created($"/users/{request.Email}", request));
```

Validation runs before the endpoint, and async errors land in the same response as the synchronous ones:

```json
{
  "title": "One or more validation errors occurred.",
  "status": 400,
  "errors": {
    "Email": ["That email is already registered."],
    "Password": ["The field Password must be a string or array type with a minimum length of '8'."]
  }
}
```

For rules that span several properties, implement `IAsyncValidatableObject` and return the results as an `IAsyncEnumerable<ValidationResult>`.

> [!NOTE]
> Async validators run concurrently where possible, so don't rely on their execution order.

#### Short-circuit endpoints

Some endpoints, like a health check, don't need authentication, CORS or any other middleware. .NET 8 added the [`ShortCircuit()`](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/routing#short-circuit-middleware-after-routing) convention, which runs the endpoint right after routing and skips the rest of the pipeline.

ASP.NET Core 11 adds the [`[ShortCircuit]` attribute](https://learn.microsoft.com/en-us/aspnet/core/release-notes/aspnetcore-11#short-circuit-endpoints-with-an-attribute), so the same works on MVC controllers and actions, not only Minimal APIs:

```csharp
app.MapGet("/health", [ShortCircuit] () => "Healthy");

// Responds with 404 without running the rest of the pipeline
app.MapGet("/favicon.ico", [ShortCircuit(404)] () => { });

[ApiController]
[Route("robots.txt")]
[ShortCircuit]
public class RobotsController : ControllerBase
{
    [HttpGet]
    public IActionResult Get() => Content("User-agent: *\nDisallow:", "text/plain");
}
```

With a logging middleware registered after routing, `/health` and `/favicon.ico` never show up in the log, while every other endpoint does.

#### Validation localization

In .NET 10, Minimal API validation messages came out in English unless you set `ErrorMessageResourceType` and `ErrorMessageResourceName` on every attribute.

In ASP.NET Core 11, [validation localization is built in](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/validation#localize-validation-messages). Register localization before validation:

```csharp
builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");
builder.Services.AddValidation();
```

`ErrorMessage` and `Display(Name)` values become resource keys:

```csharp
public class CustomerModel
{
    [Display(Name = "CustomerName")]          // resource key for the display name
    [Required(ErrorMessage = "NameRequired")] // resource key for the message
    public string? Name { get; set; }

    [Range(18, 120)]
    public int Age { get; set; }
}
```

By default, keys resolve against the resources of the type that declares the property, here `Resources/CustomerModel.resx` and `Resources/CustomerModel.de.resx`:

| Key | English | German |
| --- | --- | --- |
| `CustomerName` | Customer name | Kundenname |
| `NameRequired` | {0} is required. | {0} ist erforderlich. |
| `RangeAttribute_Error` | {0} must be between {1} and {2}. | {0} muss zwischen {1} und {2} liegen. |

An attribute without `ErrorMessage`, like `[Range]` above, falls back to naming conventions, from most to least specific:

1. `{DeclaringType}_{MemberName}_{AttributeType}_Error`
2. `{DeclaringType}_{AttributeType}_Error`
3. `{AttributeType}_Error`

If no resource matches, the attribute's default English message is used.

With the request localization middleware in place, `Accept-Language: de` returns:

```json
{
  "title": "One or more validation errors occurred.",
  "status": 400,
  "errors": {
    "Name": ["Kundenname ist erforderlich."],
    "Age": ["Age muss zwischen 18 und 120 liegen."]
  }
}
```

To keep all messages in one file, point `ValidationOptions.LocalizerProvider` at a shared resource type:

```csharp
builder.Services.AddValidation(options =>
{
    options.LocalizerProvider = (_, factory) => factory.Create(typeof(ValidationMessages));
});
```

### OpenAPI

#### Binary responses

Endpoints that return files are now [described as binary](https://learn.microsoft.com/en-us/aspnet/core/release-notes/aspnetcore-11#describe-binary-file-responses) in the OpenAPI document. That covers `FileContentResult`, `FileStreamResult`, and their Minimal API counterparts `FileContentHttpResult` and `FileStreamHttpResult`:

```csharp
app.MapGet("/invoices/{id:int}/pdf", (int id) =>
{
    byte[] pdf = InvoiceService.GeneratePdf(id);
    return TypedResults.File(pdf, MediaTypeNames.Application.Pdf, $"invoice-{id}.pdf");
})
.Produces<FileContentHttpResult>(contentType: MediaTypeNames.Application.Pdf);
```

The response references a schema with `type: string` and `format: binary`, so client generators produce a file download instead of a JSON model:

```yaml
responses:
  '200':
    description: OK
    content:
      application/pdf:
        schema:
          $ref: '#/components/schemas/FileContentHttpResult'

components:
  schemas:
    FileContentHttpResult:
      type: string
      format: binary
```

#### OpenAPI 3.2 by default

`Microsoft.AspNetCore.OpenApi` now supports [OpenAPI 3.2](https://spec.openapis.org/oas/v3.2.0.html), and it's the [new default](https://learn.microsoft.com/en-us/aspnet/core/breaking-changes/11/openapi-version-default-3-2). Calling `AddOpenApi()` without a version produces:

```yaml
openapi: '3.2.0'
```

If your tooling doesn't support 3.2, set the version explicitly:

```csharp
builder.Services.AddOpenApi(options =>
{
    options.OpenApiVersion = OpenApiSpecVersion.OpenApi3_1;
});
```

The package now depends on Microsoft.OpenApi 3.x, which has its own breaking changes. If you have custom document or operation transformers, check the [Microsoft.OpenApi upgrade guide](https://github.com/microsoft/OpenAPI.NET/blob/main/docs/upgrade-guide-3.md) before upgrading.

#### Server-Sent Events

In the [.NET 10 post](https://pavle.codes/blog/net-10/#server-sent-events-sse), I showed how `TypedResults.ServerSentEvents` streams notifications to the client:

```csharp
app.MapGet("/notifications", (CancellationToken cancellationToken) =>
    TypedResults.ServerSentEvents(GetNotifications(cancellationToken)));
```

With OpenAPI 3.2, ASP.NET Core 11 [describes each event](https://learn.microsoft.com/en-us/aspnet/core/release-notes/aspnetcore-11#server-sent-events-support-in-openapi-32) through the new `itemSchema` field:

```yaml
'/notifications':
  get:
    responses:
      '200':
        description: OK
        content:
          text/event-stream:
            itemSchema:
              required:
                - data
              type: object
              properties:
                data:
                  $ref: '#/components/schemas/Notification'
                event:
                  type: string
                id:
                  type: string
```

`event` and `id` come from `SseItem<T>`, so the schema is the same whether you stream plain values or `SseItem<Notification>` with an event type and ID. In a 3.1 document, the same schema goes under `x-oai-itemSchema`.

> [!NOTE]
> Return the stream through `TypedResults.ServerSentEvents`. A handler that returns `IAsyncEnumerable<SseItem<T>>` directly is serialized as JSON, not as an event stream.

#### HTTP QUERY

[`QUERY`](https://datatracker.ietf.org/doc/draft-ietf-httpbis-safe-method-w-body/) is a new HTTP method for read-only requests that carry a body. It's useful for searches with filters too complex for a query string, which usually end up as a `POST`.

ASP.NET Core could already map it with `MapMethods`, but in .NET 10 those endpoints were left out of the OpenAPI document. In .NET 11, [they're included](https://learn.microsoft.com/en-us/aspnet/core/release-notes/aspnetcore-11#http-query-in-generated-openapi-documents):

```csharp
public sealed record ProductSearch(string? Name, decimal MaxPrice);

app.MapMethods("/products/search", ["QUERY"], (ProductSearch search) =>
    Results.Ok(ProductService.Search(search)));
```

OpenAPI 3.2 has a `query` operation:

```yaml
/products/search:
  query:
    requestBody:
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ProductSearch'
      required: true
    responses:
      '200':
        description: OK
```

Earlier versions don't, so in a 3.1 document the same endpoint goes under an extension:

```yaml
/products/search:
  x-oai-additionalOperations:
    QUERY:
      requestBody: ...
```

#### Obsolete APIs

Marking an endpoint as deprecated in the OpenAPI document used to need a custom transformer. In ASP.NET Core 11, [`[Obsolete]` maps to `deprecated: true`](https://learn.microsoft.com/en-us/aspnet/core/release-notes/aspnetcore-11#openapi-reflects-obsolete-apis) on operations, schemas and properties:

```csharp
app.MapGet("/catalog/{id:int}", GetCatalogItem);
#pragma warning disable CS0618 // mapping an obsolete method on purpose
app.MapGet("/catalog/legacy/{id:int}", GetLegacyCatalogItem);
#pragma warning restore CS0618

[Obsolete("Use /catalog/{id}.")]
static LegacyCatalogItem GetLegacyCatalogItem(int id) => new(id, $"Product {id}", $"SKU-{id:D4}");

[Obsolete("Use CatalogItem.")]
public sealed record LegacyCatalogItem(
    int Id,
    string Name,
    [property: Obsolete("Use StockKeepingUnit.")] string Sku);
```

All three show up as deprecated:

```yaml
'/catalog/legacy/{id}':
  get:
    responses: ...
    deprecated: true

components:
  schemas:
    LegacyCatalogItem:
      type: object
      properties:
        sku:
          type: string
          deprecated: true
      deprecated: true
```

### Miscellaneous

#### MCP server template

An [MCP server](https://modelcontextprotocol.io/) exposes your own tools and data to AI hosts like GitHub Copilot, Visual Studio and VS Code. The `mcpserver` template used to need a separate install of `Microsoft.McpServer.ProjectTemplates`. In .NET 11, it [ships with the SDK](https://learn.microsoft.com/en-us/aspnet/core/release-notes/aspnetcore-11#mcp-server-template-ships-with-the-net-sdk):

```bash
# Local server over stdio (default)
dotnet new mcpserver -o OrdersMcp

# ASP.NET Core server over HTTP
dotnet new mcpserver --transport remote -o OrdersMcp
```

The HTTP version is a few lines of Minimal API setup on top of the [official C# SDK](https://github.com/modelcontextprotocol/csharp-sdk) (`ModelContextProtocol.AspNetCore`):

```csharp
var builder = WebApplication.CreateBuilder(args);

builder.Services
    .AddMcpServer()
    .WithHttpTransport(options =>
    {
        // Recommended when the server doesn't call back into the client
        options.Stateless = true;
    })
    .WithTools<RandomNumberTools>();

var app = builder.Build();
app.MapMcp();

app.Run();
```

A tool is a method marked with `[McpServerTool]`. `[Description]` tells the AI what the tool and each parameter do:

```csharp
internal class OrderTools(IOrderService orders)
{
    [McpServerTool]
    [Description("Gets the current status of an order by its number.")]
    public async Task<string> GetOrderStatus(
        [Description("Order number, for example ORD-1001")] string orderNumber,
        CancellationToken cancellationToken)
    {
        var status = await orders.GetStatusAsync(orderNumber, cancellationToken);
        return status ?? $"Order {orderNumber} was not found.";
    }
}
```

Register it next to the sample with `.WithTools<OrderTools>()`. The server lists it with an input schema generated from the method signature:

```json
{
  "name": "get_order_status",
  "description": "Gets the current status of an order by its number.",
  "inputSchema": {
    "type": "object",
    "properties": {
      "orderNumber": {
        "description": "Order number, for example ORD-1001",
        "type": "string"
      }
    },
    "required": ["orderNumber"]
  }
}
```

To use it from VS Code, add the server to `.vscode/mcp.json`:

```json
{
  "servers": {
    "orders": {
      "type": "http",
      "url": "http://localhost:6184"
    }
  }
}
```

When Copilot needs an order's status, it calls `get_order_status`. For `ORD-1001`, the tool returns `Shipped on 2026-11-20`.

#### Native OpenTelemetry tracing

ASP.NET Core 11 [adds OpenTelemetry attributes](https://learn.microsoft.com/en-us/aspnet/core/release-notes/aspnetcore-11#native-opentelemetry-tracing-for-aspnet-core) to request spans natively, so you no longer need `OpenTelemetry.Instrumentation.AspNetCore`. Subscribe to the `Microsoft.AspNetCore` activity source:

```csharp
builder.Services.AddOpenTelemetry()
    .WithTracing(tracing => tracing
        .AddSource("Microsoft.AspNetCore")
        .AddConsoleExporter());
```

A request to `GET /orders/42` produces a span with the standard attributes:

```text
Activity.DisplayName:        GET /orders/{id:int}
Activity.Kind:               Server
Activity.Tags:
    server.address: localhost
    server.port: 5400
    http.request.method: GET
    url.scheme: http
    url.path: /orders/42
    http.response.status_code: 200
    network.protocol.version: 1.1
    http.route: /orders/{id:int}
Instrumentation scope (ActivitySource):
    Name: Microsoft.AspNetCore
```

To turn the attributes off, set the `Microsoft.AspNetCore.Hosting.SuppressActivityOpenTelemetryData` AppContext switch to `true`.

#### Zstandard compression

The response compression and request decompression middleware [now support Zstandard](https://learn.microsoft.com/en-us/aspnet/core/release-notes/aspnetcore-11#zstandard-response-compression-and-request-decompression) (`zstd`), next to Brotli and gzip. It's enabled by default, so the usual setup is enough:

```csharp
builder.Services.AddResponseCompression();

var app = builder.Build();

app.UseResponseCompression();
```

For a 53 KB text response, each encoding returned:

| `Accept-Encoding` | Response size |
| --- | --- |
| `identity` | 53,892 bytes |
| `gzip` | 19,465 bytes |
| `br` | 5,648 bytes |
| `zstd` | 3,648 bytes |

When the client accepts all three, as with `Accept-Encoding: gzip, br, zstd`, the response comes back as `zstd`. To trade speed for size, set the quality level from 1 to 22:

```csharp
builder.Services.Configure<ZstandardCompressionProviderOptions>(options =>
{
    options.CompressionOptions = new ZstandardCompressionOptions { Quality = 6 };
});
```

## EF Core

> [!NOTE]
> All examples use SQL Server 2025. Vector, full-text and hybrid search are SQL Server only.

### Complex types

#### TPT and TPC inheritance

Complex types group related properties, like an address, without giving them their own table or key. Until now, they couldn't be used on a hierarchy mapped with TPT (table-per-type) or TPC (table-per-concrete-type).

Take a payment hierarchy where every payment has a billing address:

```csharp
public abstract class Payment
{
    public int Id { get; set; }
    public decimal Amount { get; set; }
    public required Address BillingAddress { get; set; }
}

public class CardPayment : Payment
{
    public required string Last4Digits { get; set; }
}

public class BankTransfer : Payment
{
    public required string Iban { get; set; }
}

public record Address(string Street, string City, string PostalCode);
```

```csharp
modelBuilder.Entity<Payment>()
    .UseTptMappingStrategy()
    .ComplexProperty(p => p.BillingAddress);
```

In EF Core 10, the database was created and the rows saved, but the first query that touched the address failed:

```text
InvalidOperationException: Sequence contains more than one element
   at Microsoft.EntityFrameworkCore.Query.SqlExpressions.SelectExpression.GenerateComplexPropertyShaperExpression(...)
```

EF Core 11 [supports both strategies](https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-11.0/whatsnew#complex-types-and-json-columns-on-entity-types-with-tpttpc-inheritance). With TPT, the address columns go to the base table:

```sql
CREATE TABLE [Payments] (
    [Id] int NOT NULL IDENTITY,
    [Amount] decimal(18,2) NOT NULL,
    [BillingAddress_City] nvarchar(max) NOT NULL,
    [BillingAddress_PostalCode] nvarchar(max) NOT NULL,
    [BillingAddress_Street] nvarchar(max) NOT NULL,
    CONSTRAINT [PK_Payments] PRIMARY KEY ([Id])
);
```

And querying by a complex property works across the hierarchy:

```csharp
var payments = await db.Payments
    .Where(p => p.BillingAddress.City == "London")
    .ToListAsync(); // returns the CardPayment
```

JSON columns are supported too, with `.ComplexProperty(p => p.BillingAddress, b => b.ToJson())`.

> [!WARNING]
> In EF Core 11.0.0, TPC with a JSON column saves data but can't read it back. Every query throws `UnreachableException: Could not find JSON container column`. Use TPT, or map the complex type to regular columns.

#### Lambda chaining, keys and indexes

Configuring a property inside a complex type took two steps:

```csharp
modelBuilder.Entity<Customer>()
    .ComplexProperty(c => c.Address)
    .Property(a => a.PostalCode)
    .HasMaxLength(10);
```

Chaining the member access in one lambda threw in EF Core 10:

```text
ArgumentException: The expression 'c => c.Address.PostalCode' is not a valid member access expression.
```

EF Core 11 [allows it](https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-11.0/whatsnew#configuring-complex-type-properties-via-lambda-chaining):

```csharp
modelBuilder.Entity<Customer>()
    .Property(c => c.Address.PostalCode)
    .HasMaxLength(10);
```

The same paths now work for [keys and indexes](https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-11.0/whatsnew#keys-and-indexes-on-complex-type-properties). That makes strongly typed IDs much easier to map, since the ID can be a complex type and its value the primary key:

```csharp
public record struct CustomerId(Guid Value);

public class Customer
{
    public CustomerId Id { get; set; }
    public required string Name { get; set; }
    public required Address Address { get; set; }
}

modelBuilder.Entity<Customer>().ComplexProperty(c => c.Id);
modelBuilder.Entity<Customer>().ComplexProperty(c => c.Address);

modelBuilder.Entity<Customer>().HasKey(c => c.Id.Value);
modelBuilder.Entity<Customer>().HasIndex(c => c.Address.PostalCode);
```

```sql
CREATE TABLE [Customers] (
    [Name] nvarchar(max) NOT NULL,
    [Id_Value] uniqueidentifier NOT NULL,
    [Address_City] nvarchar(max) NOT NULL,
    [Address_PostalCode] nvarchar(10) NOT NULL,
    [Address_Street] nvarchar(max) NOT NULL,
    CONSTRAINT [PK_Customers] PRIMARY KEY ([Id_Value])
);

CREATE INDEX [IX_Customers_Address_PostalCode] ON [Customers] ([Address_PostalCode]);
```

For relational providers, an index can also target a path inside a JSON column, such as `HasIndex("Items[].Sku")` for every item in a JSON collection.

### LINQ and SQL translation

#### Fewer joins for to-one navigations

Take an order that includes its customer (a to-one navigation) and its lines (a collection):

```csharp
var orders = await db.Orders
    .Include(o => o.Customer)
    .Include(o => o.Lines)
    .AsSplitQuery()
    .ToListAsync();
```

A split query loads the lines in a second query. In EF Core 10, that second query still joined `Customers`, even though it doesn't select anything from it:

```sql
-- EF Core 10
SELECT [o0].[Id], [o0].[OrderId], [o0].[Product], [o0].[Quantity], [o].[Id], [c].[Id]
FROM [Orders] AS [o]
LEFT JOIN [Customers] AS [c] ON [o].[CustomerId] = [c].[Id]
INNER JOIN [OrderLine] AS [o0] ON [o].[Id] = [o0].[OrderId]
ORDER BY [o].[Id], [c].[Id]
```

EF Core 11 [drops the join](https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-11.0/whatsnew#better-sql-for-to-one-joins):

```sql
-- EF Core 11
SELECT [o0].[Id], [o0].[OrderId], [o0].[Product], [o0].[Quantity], [o].[Id]
FROM [Orders] AS [o]
INNER JOIN [OrderLine] AS [o0] ON [o].[Id] = [o0].[OrderId]
ORDER BY [o].[Id]
```

It also removes the customer's key from `ORDER BY`. An order has at most one customer, so `[o].[Id]` already identifies the row. Without `AsSplitQuery()`, the single query changes from:

```sql
ORDER BY [o].[Id], [c].[Id] -- EF Core 10
ORDER BY [o].[Id]           -- EF Core 11
```

Microsoft measured a 29% improvement for a split query and 22% for a single query.

#### `FullJoin`

The [previous post](https://pavle.codes/blog/net-11/#linq-joins) covered the new LINQ `FullJoin` operator. EF Core 11 [translates it](https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-11.0/whatsnew#support-for-the-new-net-11-fulljoin-operator) to SQL's `FULL JOIN`, so it keeps customers without orders and orders without a customer:

```csharp
var rows = await db.Customers
    .FullJoin(
        db.Orders,
        c => c.Id,
        o => o.CustomerId,
        (c, o) => new
        {
            Customer = c != null ? c.Name : null,
            Total = o != null ? (decimal?)o.Total : null,
        })
    .ToListAsync();
```

```sql
SELECT [c].[Name] AS [Customer], [o].[Total]
FROM [Customers] AS [c]
FULL JOIN [Orders] AS [o] ON [c].[Id] = [o].[CustomerId]
```

```text
Alice: 120.00, Alice: 40.00, Bob: 15.00, Carol: (none), (none): 9.00
```

#### `MaxBy` and `MinBy`

EF Core 11 [translates `MaxBy` and `MinBy`](https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-11.0/whatsnew#maxby-and-minby), which return the element with the largest or smallest value, and adds async versions:

```csharp
var topCustomer = await db.Customers.MaxByAsync(c => c.Orders.Count);
```

```sql
SELECT TOP(1) [c].[Id], [c].[Name]
FROM [Customers] AS [c]
ORDER BY (
    SELECT COUNT(*)
    FROM [Orders] AS [o]
    WHERE [c].[Id] = [o].[CustomerId]) DESC
```

`MinByAsync` sorts ascending instead:

```csharp
var smallestOrder = await db.Orders.MinByAsync(o => o.Total);
```

```sql
SELECT TOP(1) [o].[Id], [o].[CustomerId], [o].[Total]
FROM [Orders] AS [o]
ORDER BY [o].[Total]
```

### Vector search

EF Core 10 added the `vector` column type through `SqlVector<float>`, and exact similarity search with `EF.Functions.VectorDistance()`. An embedding model turns text into a vector, and texts with similar meaning end up with vectors close to each other:

```csharp
public class Product
{
    public int Id { get; set; }
    public required string Name { get; set; }
    public required string Description { get; set; }
    public SqlVector<float> Embedding { get; set; }
}

modelBuilder.Entity<Product>()
    .Property(p => p.Embedding)
    .HasColumnType("vector(384)");
```

```csharp
// EmbedAsync wraps your embedding model, e.g. IEmbeddingGenerator from Microsoft.Extensions.AI
SqlVector<float> query = await EmbedAsync("cheap laptop for students");

var products = await db.Products
    .OrderBy(p => EF.Functions.VectorDistance("cosine", p.Embedding, query))
    .Take(3)
    .Select(p => p.Name)
    .ToListAsync();
// Budget notebook, Gaming laptop, Ultrabook Pro
```

"Budget notebook" ranks first, although its description never mentions "cheap", "laptop" or "students".

#### Vectors aren't loaded by default

EF Core 11 [no longer loads vector columns](https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-11.0/whatsnew#vector-properties-not-loaded-by-default) with the entity, since they're large and rarely read back:

```sql
SELECT TOP(@p) [p].[Id], [p].[Description], [p].[Name]
FROM [Products] AS [p]
ORDER BY [p].[Name]
```

They're still used in `WHERE` and `ORDER BY`, and an explicit `Select(p => p.Embedding)` loads them. Microsoft measured queries running about 9x faster against a local database and 22x against Azure SQL.

#### Vector indexes and `VectorSearch()`

`VectorDistance()` compares the query with every row. On large tables, a [vector index](https://learn.microsoft.com/en-us/ef/core/providers/sql-server/vector-search) trades a little accuracy for speed by finding *approximate* nearest neighbors.

> [!WARNING]
> Vector indexes and `VECTOR_SEARCH()` are experimental in both SQL Server and EF Core, so the APIs may change. Using them fails the build with `EF9105` until you suppress it. On SQL Server 2025, they also require the `PREVIEW_FEATURES` database setting, a table with a vector index becomes read-only, and `VectorSearch()` queries fail with a syntax error. They run on Azure SQL Database.

EF Core 11 creates the index through migrations:

```csharp
#pragma warning disable EF9105

modelBuilder.Entity<Product>()
    .HasVectorIndex(p => p.Embedding)
    .HasMetric("cosine");
```

```sql
CREATE VECTOR INDEX [IX_Products_Embedding] ON [Products]([Embedding]) WITH (METRIC = 'cosine');
```

> [!NOTE]
> The EF Core docs show `HasVectorIndex(p => p.Embedding, "cosine")`, but in EF Core 11.0.0 that string is the index name. Without `HasMetric`, model validation fails.

The new `VectorSearch()` method queries the index. `Take()` sets the number of results, and `WithApproximate()` tells SQL Server to use the index instead of scanning every row:

```csharp
var results = await db.Products
    .VectorSearch(p => p.Embedding, query, "cosine")
    .OrderBy(r => r.Distance)
    .Take(3)
    .WithApproximate()
    .ToListAsync();

foreach (var result in results)
{
    Console.WriteLine($"{result.Value.Name}: {result.Distance}");
}
```

It returns `VectorSearchResult<Product>`, which holds the entity and its distance, and translates to the `VECTOR_SEARCH()` table-valued function:

```sql
SELECT TOP(@p1) WITH APPROXIMATE [p].[Id], [p].[Description], [p].[Name], [v].[Distance]
FROM VECTOR_SEARCH(
    TABLE = [Products] AS [p],
    COLUMN = [Embedding],
    SIMILAR_TO = @p,
    METRIC = 'cosine'
) AS [v]
ORDER BY [v].[Distance]
```

### Full-text search

#### Catalogs and indexes

SQL Server's [full-text search](https://learn.microsoft.com/en-us/sql/relational-databases/search/full-text-search) needs a full-text catalog and index before you can query it. Until now, both had to be added to a migration as raw SQL:

```csharp
protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.Sql(
        "CREATE FULLTEXT CATALOG ftCatalog AS DEFAULT;",
        suppressTransaction: true);

    migrationBuilder.Sql(
        "CREATE FULLTEXT INDEX ON Articles(Title, Contents) KEY INDEX PK_Articles;",
        suppressTransaction: true);
}
```

EF Core 11 [adds both to the model](https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-11.0/whatsnew#full-text-search-catalog-and-index-creation), so migrations create and update them:

```csharp
modelBuilder.HasFullTextCatalog("ftCatalog");

modelBuilder.Entity<Article>()
    .HasFullTextIndex(a => new { a.Title, a.Contents })
    .UseKeyIndex("PK_Articles")
    .UseCatalog("ftCatalog");
```

```sql
CREATE FULLTEXT CATALOG [ftCatalog];
CREATE FULLTEXT INDEX ON [Articles]([Title], [Contents]) KEY INDEX [PK_Articles] ON [ftCatalog];
```

The index builder also sets the language per column with `UseLanguage` and the change tracking mode with `HasChangeTracking`.

#### Ranked results

`EF.Functions.FreeText()` and `EF.Functions.Contains()` have been around for years, but they only filter. You get the matching rows, with no idea which match best:

```csharp
var titles = await db.Articles
    .Where(a => EF.Functions.FreeText(a.Contents, "laptop battery"))
    .Select(a => a.Title)
    .ToListAsync();
// Gaming laptop, Ultrabook Pro, USB-C hub
```

EF Core 11 [adds `FreeTextTable` and `ContainsTable`](https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-11.0/whatsnew#full-text-search-table-valued-functions), which map to SQL Server's table-valued functions and return a `Rank` for each match. They return the entity's key, so you join back to the entity:

```csharp
var results = await db.Articles
    .FreeTextTable<Article, int>("laptop battery")
    .Join(db.Articles, ft => ft.Key, a => a.Id, (ft, a) => new { a.Title, ft.Rank })
    .OrderByDescending(r => r.Rank)
    .ToListAsync();
// Ultrabook Pro (180), USB-C hub (72), Gaming laptop (72)
```

```sql
SELECT [a0].[Title], [f].[RANK] AS [Rank]
FROM FREETEXTTABLE([Articles], *, @p) AS [f]
INNER JOIN [Articles] AS [a0] ON [f].[KEY] = [a0].[Id]
ORDER BY [f].[RANK] DESC
```

Pass `topN` to limit the results, or a column to narrow the search:

```csharp
var results = await db.Articles
    .ContainsTable<Article, int>("laptop OR notebook", a => a.Contents)
    .Join(db.Articles, ct => ct.Key, a => a.Id, (ct, a) => new { a.Title, ct.Rank })
    .OrderByDescending(r => r.Rank)
    .ToListAsync();
// Budget notebook (64), Gaming laptop (48), Ultrabook Pro (48), USB-C hub (48)
```

### Hybrid search

For "laptop for students", full-text search misses the budget notebook, while vector search ranks it first:

```text
Full-text: Gaming laptop, Ultrabook Pro, USB-C hub
Vector:    Budget notebook, Gaming laptop, Ultrabook Pro, USB-C hub, Wireless mouse
```

[Hybrid search](https://learn.microsoft.com/en-us/ef/core/providers/sql-server/vector-search#hybrid-search) runs both and adds up the scores. `FullJoin` keeps rows that only one search found:

```csharp
const int k = 5;

var results = await db.Products
    // Keyword matches, ranked 0-1000 by SQL Server
    .FreeTextTable<Product, int>(text, topN: k)
    .Join(db.Products, ft => ft.Key, p => p.Id, (ft, p) => new { Product = p, ft.Rank })
    // Semantic matches: the k closest embeddings
    .FullJoin(
        db.Products
            .OrderBy(p => EF.Functions.VectorDistance("cosine", p.Embedding, queryEmbedding))
            .Take(k)
            .Select(p => new
            {
                Product = p,
                Distance = EF.Functions.VectorDistance("cosine", p.Embedding, queryEmbedding),
            }),
        ft => ft.Product.Id,
        vs => vs.Product.Id,
        (ft, vs) => new
        {
            Name = ft.Product.Name ?? vs.Product.Name,
            FullTextRank = ft == null ? null : (int?)ft.Rank,
            Distance = vs == null ? null : (double?)vs.Distance,
        })
    // Both scores scaled to 0-1, higher is better
    .Select(r => new
    {
        r.Name,
        Score = (r.FullTextRank == null ? 0.0 : r.FullTextRank.Value / 1000.0)
              + (r.Distance == null ? 0.0 : 1.0 - r.Distance.Value),
    })
    .OrderByDescending(r => r.Score)
    .Take(3)
    .ToListAsync();
```

```text
Gaming laptop (0.75), Budget notebook (0.72), Ultrabook Pro (0.69)
```

The keyword matches get a boost, and the budget notebook stays in the results even though full-text never found it. Both searches run in one round trip:

```sql
FROM FREETEXTTABLE([Products], *, @p, @p1) AS [f]
INNER JOIN [Products] AS [p0] ON [f].[KEY] = [p0].[Id]
FULL JOIN (
    SELECT TOP(@p4) [p1].[Id], [p1].[Embedding], [p1].[Name]
    FROM [Products] AS [p1]
    ORDER BY VECTOR_DISTANCE('cosine', [p1].[Embedding], @queryEmbedding)
) AS [p2] ON [p0].[Id] = [p2].[Id]
```

### Create and apply a migration in one step

Changing the schema has always taken two commands:

```bash
dotnet ef migrations add AddProductPrice
dotnet ef database update
```

EF Core 11 [combines them](https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-11.0/whatsnew#create-and-apply-migrations-in-one-step) with the `--add` option. It creates the migration, compiles it and applies it:

```bash
dotnet ef database update InitialCreate --add
```

```text
Creating and applying migration 'InitialCreate'.
Applying migration '20261124211017_InitialCreate'.
Migration '20261124211017_InitialCreate' was successfully created and applied.
```

> [!WARNING]
> In EF Core 11.0.0, `--add` works only for the first migration. Later ones recreate every table and fail.

## Final words

This concludes the series on some of the new features in .NET 11. There's a lot more in this release than two posts can cover, so I strongly recommend the [.NET Conf 2026 playlist](https://www.youtube.com/playlist?list=PLJL9Ln_f6sGM).
