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.
Both got a long list of improvements in .NET 11 (see the full ASP.NET Core 11 and EF Core 11 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:
- Keep the connection open. By default, a WebSocket connection keeps working with the identity it started with, even after the token expires.
- Close it. With
CloseOnAuthenticationExpiration, the server drops the connection at expiry, and the client has to reconnect with a new token.
ASP.NET Core 11 adds authentication refresh, which updates the credentials of an active connection without reconnecting. You enable it per hub:
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:
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:
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:
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:
[Authorize]
public class ChatHub : Hub
{
public override Task OnAuthenticationRefreshedAsync()
{
// Context.User now holds the refreshed identity
return Clients.Caller.SendAsync("AuthenticationRefreshed", Context.UserIdentifier);
}
}
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 also cancels it on the server. Add a CancellationToken parameter to the hub method:
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:
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:
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:
HTTP/1.1 400 Bad Request
Content-Length: 0
In ASP.NET Core 11, the filter pipeline runs even when binding fails. An endpoint filter can check for the 400 status code and return its own response:
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 response:
{
"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:
builder.Services.Configure<RouteHandlerOptions>(options => options.ThrowOnBadRequest = false);
C# union types
I covered union types and their System.Text.Json support in the previous post. ASP.NET Core 11 supports them 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:
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:
{"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:
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".
Async validation
Minimal API validation in .NET 10 supported only synchronous rules. ASP.NET Core 11 adds async validation through two new DataAnnotations APIs: AsyncValidationAttribute and IAsyncValidatableObject.
For a single property, derive from AsyncValidationAttribute and implement IsValidAsync:
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:
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:
{
"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>.
Short-circuit endpoints
Some endpoints, like a health check, don’t need authentication, CORS or any other middleware. .NET 8 added the ShortCircuit() convention, which runs the endpoint right after routing and skips the rest of the pipeline.
ASP.NET Core 11 adds the [ShortCircuit] attribute, so the same works on MVC controllers and actions, not only Minimal APIs:
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. Register localization before validation:
builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");
builder.Services.AddValidation();
ErrorMessage and Display(Name) values become resource keys:
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:
{DeclaringType}_{MemberName}_{AttributeType}_Error{DeclaringType}_{AttributeType}_Error{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:
{
"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:
builder.Services.AddValidation(options =>
{
options.LocalizerProvider = (_, factory) => factory.Create(typeof(ValidationMessages));
});
OpenAPI
Binary responses
Endpoints that return files are now described as binary in the OpenAPI document. That covers FileContentResult, FileStreamResult, and their Minimal API counterparts FileContentHttpResult and FileStreamHttpResult:
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:
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, and it’s the new default. Calling AddOpenApi() without a version produces:
openapi: '3.2.0'
If your tooling doesn’t support 3.2, set the version explicitly:
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 before upgrading.
Server-Sent Events
In the .NET 10 post, I showed how TypedResults.ServerSentEvents streams notifications to the client:
app.MapGet("/notifications", (CancellationToken cancellationToken) =>
TypedResults.ServerSentEvents(GetNotifications(cancellationToken)));
With OpenAPI 3.2, ASP.NET Core 11 describes each event through the new itemSchema field:
'/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.
HTTP QUERY
QUERY 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:
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:
/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:
/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 on operations, schemas and properties:
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:
'/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 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:
# 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 (ModelContextProtocol.AspNetCore):
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:
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:
{
"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:
{
"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 to request spans natively, so you no longer need OpenTelemetry.Instrumentation.AspNetCore. Subscribe to the Microsoft.AspNetCore activity source:
builder.Services.AddOpenTelemetry()
.WithTracing(tracing => tracing
.AddSource("Microsoft.AspNetCore")
.AddConsoleExporter());
A request to GET /orders/42 produces a span with the standard attributes:
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 (zstd), next to Brotli and gzip. It’s enabled by default, so the usual setup is enough:
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:
builder.Services.Configure<ZstandardCompressionProviderOptions>(options =>
{
options.CompressionOptions = new ZstandardCompressionOptions { Quality = 6 };
});
EF Core
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:
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);
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:
InvalidOperationException: Sequence contains more than one element
at Microsoft.EntityFrameworkCore.Query.SqlExpressions.SelectExpression.GenerateComplexPropertyShaperExpression(...)
EF Core 11 supports both strategies. With TPT, the address columns go to the base table:
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:
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()).
Lambda chaining, keys and indexes
Configuring a property inside a complex type took two steps:
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:
ArgumentException: The expression 'c => c.Address.PostalCode' is not a valid member access expression.
EF Core 11 allows it:
modelBuilder.Entity<Customer>()
.Property(c => c.Address.PostalCode)
.HasMaxLength(10);
The same paths now work for keys and indexes. That makes strongly typed IDs much easier to map, since the ID can be a complex type and its value the primary key:
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);
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):
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:
-- 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:
-- 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:
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 covered the new LINQ FullJoin operator. EF Core 11 translates it to SQL’s FULL JOIN, so it keeps customers without orders and orders without a customer:
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();
SELECT [c].[Name] AS [Customer], [o].[Total]
FROM [Customers] AS [c]
FULL JOIN [Orders] AS [o] ON [c].[Id] = [o].[CustomerId]
Alice: 120.00, Alice: 40.00, Bob: 15.00, Carol: (none), (none): 9.00
MaxBy and MinBy
EF Core 11 translates MaxBy and MinBy, which return the element with the largest or smallest value, and adds async versions:
var topCustomer = await db.Customers.MaxByAsync(c => c.Orders.Count);
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:
var smallestOrder = await db.Orders.MinByAsync(o => o.Total);
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:
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)");
// 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 with the entity, since they’re large and rarely read back:
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 trades a little accuracy for speed by finding approximate nearest neighbors.
EF Core 11 creates the index through migrations:
#pragma warning disable EF9105
modelBuilder.Entity<Product>()
.HasVectorIndex(p => p.Embedding)
.HasMetric("cosine");
CREATE VECTOR INDEX [IX_Products_Embedding] ON [Products]([Embedding]) WITH (METRIC = 'cosine');
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:
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:
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 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:
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, so migrations create and update them:
modelBuilder.HasFullTextCatalog("ftCatalog");
modelBuilder.Entity<Article>()
.HasFullTextIndex(a => new { a.Title, a.Contents })
.UseKeyIndex("PK_Articles")
.UseCatalog("ftCatalog");
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:
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, 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:
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)
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:
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:
Full-text: Gaming laptop, Ultrabook Pro, USB-C hub
Vector: Budget notebook, Gaming laptop, Ultrabook Pro, USB-C hub, Wireless mouse
Hybrid search runs both and adds up the scores. FullJoin keeps rows that only one search found:
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();
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:
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:
dotnet ef migrations add AddProductPrice
dotnet ef database update
EF Core 11 combines them with the --add option. It creates the migration, compiles it and applies it:
dotnet ef database update InitialCreate --add
Creating and applying migration 'InitialCreate'.
Applying migration '20261124211017_InitialCreate'.
Migration '20261124211017_InitialCreate' was successfully created and applied.
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.