Friday, September 11, 2026

EF Core 11.0: What's New with Migrations

.NET 11 Release Candidate 1 is out, and that means we are getting really close to the finish line. Next month we should get RC2, and then in November the GA release at .NET Conf 2026. You can read more about RC1 here: Announcing .NET 11 Release Candidate 1.

In this post, let's have a look at some of the nice improvements that are coming to EF Core 11.0 Migrations. There are quite a few of them, but I am going to focus on the following three.
  • Excluding foreign key constraints from migrations
  • Create and apply migrations in one step
  • Connection and offline options for migrations remove
First, the project file. I am using the latest RC as of today, it will change.
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net11.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="11.0.0-rc.1.26425.128">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="11.0.0-rc.1.26425.128" />
  </ItemGroup>

</Project>

And make sure you have the matching version of the dotnet-ef tool.
dotnet tool update -g dotnet-ef --version 11.0.0-rc.1.26425.128

Excluding foreign key constraints from migrations


Say you are working with a legacy database that doesn't have foreign key constraints, or you have some data synchronization process where referential integrity constraints get in the way of the synchronization order. You still want EF Core to know about the relationship, but you don't want migrations to create the constraint in the database.

With EF Core 11.0, we now have ExcludeForeignKeyFromMigrations() for exactly that. Consider the following entities.
public class Customer
{
    public int Id { get; set; }

    public string Name { get; set; }
}

public class Order
{
    public int Id { get; set; }

    public string OrderNumber { get; set; }

    public Customer Customer { get; set; }

    public int CustomerId { get; set; }
}
And here is the DbContext. The relationship is configured as usual, and we just call ExcludeForeignKeyFromMigrations() at the end.
public class MyDbContext : DbContext
{
    public DbSet<Customer> Customers { get; set; }

    public DbSet<Order> Orders { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder
            .UseSqlServer(@"<ConnectionString>")
            .LogTo(Console.WriteLine, LogLevel.Information);
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Order>()
            .HasOne(x => x.Customer)
            .WithMany()
            .HasForeignKey(x => x.CustomerId)
            .ExcludeForeignKeyFromMigrations();
    }
}
When we add a migration, the Orders table no longer has a ForeignKey constraint. Note that an index is still created on the foreign key column.
protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.CreateTable(
        name: "Customers",
        columns: table => new
        {
            Id = table.Column<int>(type: "int", nullable: false)
                .Annotation("SqlServer:Identity", "1, 1"),
            Name = table.Column<string>(type: "nvarchar(max)", nullable: false)
        },
        constraints: table =>
        {
            table.PrimaryKey("PK_Customers", x => x.Id);
        });

    migrationBuilder.CreateTable(
        name: "Orders",
        columns: table => new
        {
            Id = table.Column<int>(type: "int", nullable: false)
                .Annotation("SqlServer:Identity", "1, 1"),
            OrderNumber = table.Column<string>(type: "nvarchar(max)", nullable: false),
            CustomerId = table.Column<int>(type: "int", nullable: false)
        },
        constraints: table =>
        {
            table.PrimaryKey("PK_Orders", x => x.Id);
        });

    migrationBuilder.CreateIndex(
        name: "IX_Orders_CustomerId",
        table: "Orders",
        column: "CustomerId");
}
The relationship itself is fully supported in EF Core for queries, change tracking etc. Only the constraint in the database is suppressed.
using var context = new MyDbContext();

Customer customer = new() 
{
Name = "John Doe"
}; await context.Customers.AddAsync(customer); await context.Orders.AddRangeAsync( new Order { OrderNumber = "ORD-001", Customer = customer }, new Order { OrderNumber = "ORD-002", Customer = customer }); await context.SaveChangesAsync(); foreach (Order order in await context.Orders .Include(x => x.Customer) .ToListAsync()) { Console.WriteLine($"Order: '{order.OrderNumber}', Customer: '{order.Customer.Name}'."); } // Query //SELECT[o].[Id], [o].[CustomerId], [o].[OrderNumber], [c].[Id], [c].[Name] //FROM[Orders] AS[o] //INNER JOIN[Customers] AS [c] ON[o].[CustomerId] = [c].[Id] // Output // Order: 'ORD-001', Customer: 'John Doe'. // Order: 'ORD-002', Customer: 'John Doe'

Create and apply migrations in one step


Up until now, create and apply migrations has always been two commands: dotnet ef migrations add followed by dotnet ef database update. With EF Core 11.0, dotnet ef database update has a new --add option that scaffolds the migration, compiles it at runtime using Roslyn, and applies it to the database, all in one go.
dotnet ef database update InitialCreate --add
And the output (trimmed):
Build started...
Build succeeded.
Creating and applying migration 'InitialCreate'.
...
Applying migration '20260911004844_InitialCreate'.
...
      CREATE TABLE [Customers] (
          [Id] int NOT NULL IDENTITY,
          [Name] nvarchar(max) NOT NULL,
          CONSTRAINT [PK_Customers] PRIMARY KEY ([Id])
      );
...
      CREATE TABLE [Orders] (
          [Id] int NOT NULL IDENTITY,
          [OrderNumber] nvarchar(max) NOT NULL,
          [CustomerId] int NOT NULL,
          CONSTRAINT [PK_Orders] PRIMARY KEY ([Id])
      );
...
      CREATE INDEX [IX_Orders_CustomerId] ON [Orders] ([CustomerId]);
...
Migration '20260911004844_InitialCreate' was successfully created and applied.
The migration files are still written to disk, so you can commit them to source control as usual. All the options you would use with dotnet ef migrations add are supported as well.

If you are using the Package Manager Console, you can use the -Add parameter.
Update-Database -Migration InitialCreate -Add

Connection and offline options for migrations remove


dotnet ef migrations remove and dotnet ef database drop now accept a --connection option, so we can pass in the connection string directly instead of relying on whatever is configured in the DbContext.
# Remove migration using a specific connection
dotnet ef migrations remove --connection "<Connection String>"

# Drop a specific database using a connection string
dotnet ef database drop --connection "<Connection String>" --force
And migrations remove has a new --offline option. Previously, migrations remove always connected to the database to check whether the migration had been applied. With --offline, that check is skipped entirely, which is useful when the database isn't reachable or when you know the migration hasn't been applied.
dotnet ef migrations add InitialCreate
dotnet ef migrations remove --offline
And the output:
Build started...
Build succeeded.
Removing migration '20260911004851_AddOrderDate'.
Reverting the model snapshot.
Done.
Note that --offline and --force can't be used together. --force reverts the migration if it has been applied, and to know that, it needs a database connection.
# The --offline and --force options cannot be used together.
dotnet ef migrations remove --offline --force
In the Package Manager Console, use the -Connection and -Offline parameters.
Remove-Migration -Connection "<Connection String>"
Remove-Migration -Offline
Drop-Database -Connection "<Connection String>" -Force
There are more migration improvements in EF Core 11.0 like the latest migration ID being recorded in the model snapshot, a configuration file for dotnet ef, -NoBuild for PMC commands, and wildcard context support. Do check them out.

More read:

Hope this helps.

Happy Coding.

Regards,
Jaliya

Monday, August 24, 2026

Azure DevOps: Copy Azure Container Registry (ACR) Images to an External Tenant's ACR

Consider a scenario where an App Service running in an external tenant needs to pull an image from our own ACR. The lazy way is to share our ACR credentials (username/password) with the external party, so they can set DOCKER_REGISTRY_SERVER_USERNAME and DOCKER_REGISTRY_SERVER_PASSWORD.

But obviously that's not something we should be doing. We can't be handing our own passwords to anyone, and we shouldn't be using passwords or secrets in the first place.

You might think the fix is for them to give their App Service a managed identity and grant it AcrPull on our ACR. That doesn't work across tenants. A managed identity only exists in its own tenant.

What does work is copying the image into their ACR first. Then their App Service pulls from their own registry, in their own tenant, with their own managed identity, and that's just the ordinary same-tenant case.

So in this post, let's see how we can copy Azure Container Registry (ACR) images to an external tenant's ACR in Azure DevOps..

Prerequisites
  • Both registries need public network access. A registry on Selected networks still counts as enabled, but it also has to allow trusted Azure services to bypass the network, which is on by default.
  • Both registries accept Entra ARM tokens. You can test it using the following script.
$TENANT_ID = "<TENANT_ID>"
$SUBSCRIPTION_ID = "<SUBSCRIPTION_ID>"

$ACR_RESOURCE_GROUP_NAME = "<ACR_RESOURCE_GROUP_NAME>"
$ACR_NAME = "<ACR_NAME>"
$ACR_RESOURCE_ID = "/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$ACR_RESOURCE_GROUP_NAME/providers/Microsoft.ContainerRegistry/registries/$ACR_NAME"

# Login to tenant and set the subscription
az login `
  --tenant $TENANT_ID

az account set `
  --subscription $SUBSCRIPTION_ID

# Confirm the registry accepts Entra ARM tokens
az rest `
  --method get `
  --url "https://management.azure.com$ACR_RESOURCE_ID`?api-version=2023-01-01-preview" `
  --query "properties.policies.azureADAuthenticationAsArmPolicy.status" `
  --output tsv

The concept

  • Two Azure DevOps service connections, both in our project, each federated to a different managed identity in a different tenant. No secret in either one, just a trust.
  • Ours/Source: A user-assigned managed identity with AcrPull on our ACR, and a service connection federated to it. We add the federated credential to that identity ourselves, because it lives in our tenant.
    • If your source registry is ABAC-enabled, grant Container Registry Repository Reader instead. AcrPull isn't honoured there.
  • Theirs/External:  A user-assigned managed identity with Container Registry Data Importer and Data Reader on their ACR. We create the second service connection pointing at their tenant, and send them the Issuer and Subject it generates. They add the federated credential to their identity.
  • At deploy time the pipeline mints a short-lived token using the first connection, then calls az acr import with the second connection.

az acr import `
  --name "<THEIR_ACR_NAME>" `
  --resource-group "<THEIR_ACR_RESOURCE_GROUP_NAME>" `
  --source "<OUR_ACR_LOGIN_SERVER>/<IMAGE_NAME>:<IMAGE_TAG>" `
  --image "<IMAGE_NAME>:<IMAGE_TAG>" `
  --password "<ACCESS_TOKEN_CREATED_USING_OUR_SERVICE_CONNECTION>"

    • Note there is no --username. The access token is only accepted as a lone --password, and adding a username turns it into a basic auth pair.
    • az acr import authenticates the source and the target separately. 
    • The call goes to their registry as an identity in their tenant, and our registry is named in the same request with its own credential alongside. 
    • Their registry then pulls the image straight from ours, server to server, so the build agent never downloads it.

Now let's see this in action.

Some variables.

$SOURCE_TENANT_ID = "<OUR_TENANT_ID>"
$SOURCE_SUBSCRIPTION_ID = "<OUR_SUBSCRIPTION_ID>"

# Identity
$MIRROR_IDENTITY_NAME = "<MANAGED_IDENTITY_NAME>"
$MIRROR_IDENTITY_RESOURCE_GROUP_NAME = "<MANAGED_IDENTITY_RESOURCE_GROUP_NAME>"
$MIRROR_IDENTITY_LOCATION = "<LOCATION>"

# Source ACR
$SOURCE_ACR_RESOURCE_GROUP_NAME = "<ACR_RESOURCE_GROUP>"
$SOURCE_ACR_NAME = "<ACR_NAME>"
$SOURCE_ACR_RESOURCE_ID = "/subscriptions/$SOURCE_SUBSCRIPTION_ID/resourceGroups/$SOURCE_ACR_RESOURCE_GROUP_NAME/providers/Microsoft.ContainerRegistry/registries/$SOURCE_ACR_NAME"

First step is creating a Managed Identity.

# Login to the tenant and set subscription
az login `
  --tenant $SOURCE_TENANT_ID

az account set `
  --subscription $SOURCE_SUBSCRIPTION_ID

# Create a user-assigned managed identity
az identity create `
  --name $MIRROR_IDENTITY_NAME `
  --resource-group $MIRROR_IDENTITY_RESOURCE_GROUP_NAME `
  --subscription $SOURCE_SUBSCRIPTION_ID `
  --location $MIRROR_IDENTITY_LOCATION

$sourceIdentity = az identity show `
  --name $MIRROR_IDENTITY_NAME `
  --resource-group $MIRROR_IDENTITY_RESOURCE_GROUP_NAME `
  --subscription $SOURCE_SUBSCRIPTION_ID | ConvertFrom-Json

$MIRROR_IDENTITY_PRINCIPAL_ID = $sourceIdentity.principalId
$MIRROR_IDENTITY_CLIENT_ID = $sourceIdentity.clientId

Now let's grant the MI AcrPull OR Container Registry Repository Reader on our ACR.

# Assign the AcrPull OR Container Registry Repository Reader role to the managed identity
az role assignment create `
  --assignee-object-id $MIRROR_IDENTITY_PRINCIPAL_ID `
  --assignee-principal-type ServicePrincipal `
  --role "<AcrPull OR Container Registry Repository Reader>" `
  --scope $SOURCE_ACR_RESOURCE_ID

Now let's create the source Service Connection.

New Service Connection: Azure Resource Manager

Note: 

  • Identity Type: App registration or managed identity (manual)
  • Credential: Workload identity federation
  • Directory (tenant) ID: Our Tenant ID.

New Service Connection App Registration Details
Here, the Application (client) ID is the MIRROR_IDENTITY_CLIENT_ID.

Now before clicking on Verify and save, run the following using displayed Issuer and Subject identifier to create federated credentials.

# Create federated credential for the managed identity
az identity federated-credential create `
  --name azure-devops-mirror-source `
  --identity-name $MIRROR_IDENTITY_NAME `
  --resource-group $MIRROR_IDENTITY_RESOURCE_GROUP_NAME `
  --subscription $SOURCE_SUBSCRIPTION_ID `
  --issuer "<Issuer>" `
  --subject "<Subject identifier>" `
  --audiences "api://AzureADTokenExchange"
After this is executed, wait for a few seconds and then click on Verify and save. It should be verified and saved successfully.

Now we need to configure the external side. Almost all of the steps are exact same as above with different values. On external side,
  • The managed identity needs to be granted role: Container Registry Data Importer and Data Reader on their ACR.
  • To create the second service connection, the only thing we need from them up front is their Tenant ID. Note the Directory (tenant) ID is their tenant, not ours.
    • Fill in the tenant id, move to the next step, and Azure DevOps generates the Issuer and Subject identifier. Copy both and select Keep as draft
    • Send them the Issuer and Subject identifier so they can create the federated credential on their managed identity. When they confirm, they need to send back the following
      • Subscription ID
      • Subscription Name
      • ACR Name
      • ACR Resource Group Name
      • Client ID of their Managed Identity
    • Once the information is received, go back to the draft connection, fill those in, then Finish setup and Verify and save.
One caution: Tenant ID cannot be edited after the connection is created. If it is wrong, you have to delete the connection and create a new one, and therefore a new Subject identifier, so the federated credential has to be recreated as well.

At this point, second service connection should be verified and saved successfully.

Now the moment of truth. We can create a simple pipeline to test the az acr import end-to-end.
trigger: none
pr: none

parameters:
  - name: sourceImageName
    displayName: Source image, repository:tag with no host
    type: string
    default: <IMAGE_NAME>:<IMAGE_TAG>

pool:
  vmImage: ubuntu-latest

variables:
  sourceServiceConnection: <SOURCE_SERVICE_CONNECTION_NAME>
  targetServiceConnection: <EXTERNAL_SERVICE_CONNECTION_NAME>
  sourceAcrLoginServer: <SOURCE_ACR_NAME>.azurecr.io
  targetAcrName: <TARGET_ACR_NAME>
  targetAcrResourceGroup: <TARGET_ACR_RESOURCE_GROUP>

steps:
  - task: AzureCLI@2
    displayName: Get source ACR read token
    inputs:
      azureSubscription: $(sourceServiceConnection)
      scriptType: pscore
      scriptLocation: inlineScript
      inlineScript: |
        az account show `
          --query "{tenant:tenantId, subscription:name, id:id, principal:user.name}" `
          --output table

        $SOURCE_ACCESS_TOKEN = (az account get-access-token `
          --query accessToken `
          --output tsv).Trim()

        Write-Host "##vso[task.setvariable variable=sourceAccessToken;issecret=true]$SOURCE_ACCESS_TOKEN"

  - task: AzureCLI@2
    displayName: Import image into target ACR
    inputs:
      azureSubscription: $(targetServiceConnection)
      scriptType: pscore
      scriptLocation: inlineScript
      inlineScript: |
        az account show `
          --query "{tenant:tenantId, subscription:name, id:id, principal:user.name}" `
          --output table

        az acr import `
          --name "$(targetAcrName)" `
          --resource-group "$(targetAcrResourceGroup)" `
          --source "$(sourceAcrLoginServer)/${{ parameters.sourceImageName }}" `
          --image "${{ parameters.sourceImageName }}" `
          --password "$(sourceAccessToken)" `
          --force

  - task: AzureCLI@2
    displayName: Confirm the tag landed
    inputs:
      azureSubscription: $(targetServiceConnection)
      scriptType: pscore
      scriptLocation: inlineScript
      inlineScript: |
        $IMAGE_NAME = "${{ parameters.sourceImageName }}"

        az acr repository show-tags `
          --name "$(targetAcrName)" `
          --repository ($IMAGE_NAME.Split(":")[0]) `
          --output table
And when you run this, it should do the import.
Pipeline Run
Hope this helps.

Happy Coding.

Regards,
Jaliya

Thursday, August 20, 2026

Use of AZURE_TOKEN_CREDENTIALS in Azure.Identity

In this post, let's have a look at the AZURE_TOKEN_CREDENTIALS environment variable in Azure.Identity. I only came across it recently, and it has removed something that used to annoy me every single day.

We all know why we should be authenticating to Azure services with Microsoft Entra ID rather than with keys, connection strings or passwords. 
TokenCredential credential = new DefaultAzureCredential();
When I am working on something locally, what I used to do is grant my own Azure account access to the development resource, sign in through Visual Studio or the Azure CLI, and let DefaultAzureCredential pick that identity up. 

But this can be a pain when running locally. DefaultAzureCredential is a chain. It attempts credentials one after the other, in order, and the first one that returns a token wins. The deployed service credentials (EnvironmentCredentialWorkloadIdentityCredentialManagedIdentityCredential) come first and then the developer tool credentials like VisualStudioCredentialAzureCliCredential, AzureDeveloperCliCredential etc.

In our local machine, deployed credentials obviously won't work, but still it will get tried. ManagedIdentityCredential is the worst among them, because it actually goes out to the Azure Instance Metadata Service (IMDS) endpoint at 169.254.169.254 and only gives up once that socket fails or times out. So every run and every debug session pays for these guaranteed failures.

Let's look by an example. I am using latest Azure.Identity package as of today.
<PackageReference Include="Azure.Identity" Version="1.21.0" />
Here is the basic code.
using Azure.Core;
using Azure.Core.Diagnostics;
using Azure.Identity;
using System.Diagnostics.Tracing;

using AzureEventSourceListener listener = new((eventArgs, message) =>
{
    // Helper method to print out the provider
    PrintProvider(eventArgs, message);
}, EventLevel.Informational);

TokenCredential credential = new DefaultAzureCredential();

// Omitted: some call that exercises the credentials

Console.WriteLine("\nDone");
When I run this, I can see something like below:
Trying   : DefaultAzureCredential
Trying   : EnvironmentCredential
Trying   : WorkloadIdentityCredential
Trying   : ManagedIdentityCredential
Trying   : VisualStudioCredential
Selected : VisualStudioCredential

Done
You can see all the credentials it's trying and it takes unnecessary time. For a long time my workaround was to branch on the environment, and when running in Development, switch off the credentials that were never going to work anyway, using the Exclude prefixed properties on DefaultAzureCredentialOptions, something like below.
TokenCredential credential = new DefaultAzureCredential();

// Environment check, could be ASPNETCORE_ENVIRONMENT, AZURE_FUNCTIONS_ENVIRONMENT etc.
bool isDevelopment = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") == "Development";
if (isDevelopment)
{
    credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions
    {
        ExcludeEnvironmentCredential = true,
        ExcludeWorkloadIdentityCredential = true,
        ExcludeManagedIdentityCredential = true,
    });
}
With this, it will print something like this.
Trying   : DefaultAzureCredential
Trying   : VisualStudioCredential
Selected : VisualStudioCredential

Done
It works, but it's a pain to do this in each project I am working on.

Since Azure.Identity 1.14.0, all of the above can be replaced with an environment variable. Set AZURE_TOKEN_CREDENTIALS to dev and the chain drops every deployed service credential, leaving only the developer tool ones.
{
  "profiles": {
    "ConsoleApp1": {
      "commandName": "Project",
      "environmentVariables": {
        "DOTNET_ENVIRONMENT": "Development",
        "AZURE_TOKEN_CREDENTIALS": "dev"
      }
    }
  }
}

And the code then goes back to being the single line.
TokenCredential credential = new DefaultAzureCredential();
Exactly the same outcome as the Exclude block, with no branching, nothing to maintain. It is purely configuration.

One thing to keep in mind is that if AZURE_TOKEN_CREDENTIALS isn't set at all, DefaultAzureCredential quietly falls back to the full chain. So if someone clones the repo without the launch profile, or the variable gets dropped somewhere along the way, you are silently back to where you started. If you would rather fail fast, since Azure.Identity 1.16.0 there is a constructor overload that takes the environment variable name and requires it to be set to a valid value.
TokenCredential credential =
    new DefaultAzureCredential(DefaultAzureCredential.DefaultEnvironmentVariableName);
Now if it's missing, you get a clear error instead of a silent fallback.
Unhandled exception. 
System.InvalidOperationException: Environment variable 'AZURE_TOKEN_CREDENTIALS' is not set or is empty.
And if you typo the value, it throws as well and lists every value it accepts, which is quite handy.

There is a prod value too, which does the opposite and keeps only the deployed service credentials. And from Azure.Identity 1.15.0 onwards you can go further and name a single credential, which reduces the chain to just that one. The comparison is case insensitive.
"AZURE_TOKEN_CREDENTIALS": "VisualStudioCredential"
A small feature, but if you have been quietly copying that Exclude block around for years like I have, it is a life saver.

Happy Coding.

Regards,
Jaliya

Thursday, August 13, 2026

Using Azure AI Foundry resource for .NET Azure.AI.TextAnalytics and Azure.AI.Translation.Text Clients

In this post, let's see how we can move .NET clients from consuming Azure AI Language and Azure AI Translator resource onto a single Azure AI Foundry resource.

I had some .NET code using TextAnalyticsClient (Azure.AI.TextAnalytics) and TextTranslationClient (Azure.AI.Translation.Text). These were pointing to two different Azure AI resources.
// API Kind: TextAnalytics
https://lang-demo-service-001.cognitiveservices.azure.com

// API Kind: TextTranslation
https://trsl-demo-service-001.cognitiveservices.azure.com
These are the NuGet packages (latest as of today, it will change).
<ItemGroup>
  <PackageReference Include="Azure.AI.TextAnalytics" Version="5.3.0" />
  <PackageReference Include="Azure.AI.Translation.Text" Version="2.0.0" />
  <PackageReference Include="Azure.Identity" Version="1.21.0" />
</ItemGroup>
And this is the existing code.
using Azure;
using Azure.AI.TextAnalytics;
using Azure.AI.Translation.Text;
using Azure.Identity;

DefaultAzureCredential credentials = new DefaultAzureCredential();

// API Kind: TextAnalytics
string languageEndpoint = "https://lang-demo-service-001.cognitiveservices.azure.com";

TextAnalyticsClient textAnalyticsClient = new(new Uri(languageEndpoint), credentials);
Azure.AI.TextAnalytics.DetectedLanguage response =
    await textAnalyticsClient.DetectLanguageAsync("Hello");
Console.WriteLine(response.Name);

// API Kind: TextTranslation
string translatorEndpoint = "https://trsl-demo-service-001.cognitiveservices.azure.com";

TextTranslationClient textTranslationClient = new(credentials, new Uri(translatorEndpoint));
Response<IReadOnlyList<TranslatedTextItem>> translateTextResponse =
    await textTranslationClient.TranslateAsync("fr", "Hello", "en");

TranslatedTextItem? translatedTextItem = translateTextResponse.Value.FirstOrDefault();
Console.WriteLine(translatedTextItem?.Translations.FirstOrDefault()?.Text);
I didn't want to maintain more services when we can have single Microsoft Foundry resource (API Kind: AIServices). It's a multi-service resource, it bundles Language, Translator, Speech, Vision and more, so it's one resource, one credential and one endpoint in configuration.

I thought that should be a simple endpoint change.
string apiEndpoint = "https://aif-demo-service-001.services.ai.azure.com";

DefaultAzureCredential credentials = new DefaultAzureCredential();

// Language
TextAnalyticsClient textAnalyticsClient = new(new Uri(apiEndpoint), credentials);

// Translation
TextTranslationClient textTranslationClient = new(credentials, new Uri(apiEndpoint));

// Omitted for brevity
TextAnalyticsClient seemed to work, it wrote out English. But TextTranslationClient didn't.
English

Unhandled exception. Azure.RequestFailedException: Resource not found Status: 404(Resource Not Found) ErrorCode: 404 Content: { "error":{ "code":"404","message": "Resource not found"} } Headers: apim - request - id: REDACTED Strict-Transport-Security: REDACTED X-Content-Type-Options: REDACTED Date: Tue, 11 Aug 2026 08:57:57 GMT Content-Length: 56 Content - Type: application / json at Azure.AI.Translation.Text.ClientPipelineExtensions.ProcessMessageAsync(HttpPipeline pipeline, HttpMessage message, RequestContext context) at Azure.AI.Translation.Text.TextTranslationClient.TranslateAsync(RequestContent content, String clientTraceId, RequestContext context) at Azure.AI.Translation.Text.TextTranslationClient.TranslateAsync(IEnumerable`1 inputs, CancellationToken cancellationToken) at Program.< Main >$(String[] args) in C: \Users\Jaliya\Desktop\ConsoleApp1\ConsoleApp1\Program.cs:line 45 at Program.<Main>(String[] args)
My first thought was that Translator simply isn't served on the services.ai.azure.com endpoint. That's not it, a raw request against the very same endpoint works.
$token = az account get-access-token `
    --resource https://cognitiveservices.azure.com `
    --query accessToken -o tsv

curl -X POST "https://aif-demo-service-001.services.ai.azure.com/translator/text/v3.0/translate?api-version=3.0&to=fr" `
     -H "Authorization: Bearer $token" `
     -H "Content-Type: application/json" `
     -d "[{'Text':'Hello'}]"

# 200 OK
#[
#    {
#        "detectedLanguage": {
#            "language": "en",
#            "score": 1.0
#        },
#        "translations": [
#            {
#                "text": "Bonjour",
#                "to": "fr"
#            }
#        ]
#    }
#]     
So the host is fine, and note the route, Translator lives under /translator/text. May be something fishy with the SDK.

Looking at the source of Azure.AI.Translation.Text, this is how it decides whether to add that route prefix.
private const string PLATFORM_HOST = "cognitiveservices";

internal static bool IsPlatformHost(this Uri uri)
{
    return uri.Host?.Contains(PLATFORM_HOST) == true;
}
Which is then used in the constructor.
private const string PLATFORM_PATH = "/translator/text";

if (endpoint.IsPlatformHost())
{
    this._endpoint = new Uri(endpoint, PLATFORM_PATH);
}
There it is. The prefix is added only when the endpoint host contains the literal string cognitiveservices.

My old endpoint was trsl-demo-service-001.cognitiveservices.azure.com, which contains it, so the SDK built /translator/text/translate. The new one is aif-demo-service-001.services.ai.azure.com, which doesn't, so the SDK treated it like a global endpoint and posted to /translate. Hence the 404.

The fix is to pass the prefix ourselves when constructing the Uri.
using Azure;
using Azure.AI.Translation.Text;
using Azure.Identity;

string apiEndpoint = "https://aif-inf-sl-tenant1-dev-001.services.ai.azure.com";

DefaultAzureCredential credentials = new DefaultAzureCredential();

// Translation
TextTranslationClient textTranslationClient = new(credentials, new Uri($"{apiEndpoint}/translator/text"));
Response<IReadOnlyList<TranslatedTextItem>> translateTextResponse =
    await textTranslationClient.TranslateAsync("fr", "Hello", "en");

TranslatedTextItem? translatedTextItem = translateTextResponse.Value.FirstOrDefault();
Console.WriteLine(translatedTextItem?.Translations.FirstOrDefault()?.Text);
And now both work off the single endpoint.
English
Bonjour
One thing I wanted to confirm, what happens if a future version of the SDK starts recognizing services.ai.azure.com? Would it add the prefix on top of mine and put me back at a 404? No, because PLATFORM_PATH is rooted, so new Uri(endpoint, PLATFORM_PATH) replaces the path instead of appending to it.
Uri uri = new Uri(new Uri("https://aif-demo-service-001.services.ai.azure.com/translator/text"), "/translator/text");
Console.WriteLine(uri.ToString());

// https://aif-demo-service-001.services.ai.azure.com/translator/text
I have raised this with the SDK team as azure-sdk-for-net#61912, so the behavior might change.

More read:

Hope this helps.

Happy Coding.

Regards,
Jaliya

Sunday, August 9, 2026

Support for C# 15 Union Types in ASP.NET Core

In this post, let's have a look at how Union types in C# 15 flow through an ASP.NET Core minimal API and how they are described in OpenAPI. This is a follow up to my previous post C# 15: Brand New Union Types, so I will reuse the same Shape union.

Everything here runs on .NET 11 Preview 6 (latest as of today, it will change) and the Microsoft.AspNetCore.OpenApi package for the built in OpenAPI document generation.

Also using latest language features.
<LangVersion>preview</LangVersion>
Here is a single endpoint that returns a Shape.
using Microsoft.AspNetCore.Http.HttpResults;

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

builder.Services.AddOpenApi();

WebApplication app = builder.Build();

app.MapOpenApi();

app
    .MapGet("/shapes/{id}", Results<Ok<Shape>, NotFound> (int id) =>
    {
        Dictionary<int, Shape> shapes = new()
        {
            { 1, new Circle(2) },
            { 2, new Rectangle(3, 4) },
            { 3, new Triangle(4, 5) }
        };

        return shapes.TryGetValue(id, out var shape)
            ? TypedResults.Ok(shape)
            : TypedResults.NotFound();
    })
    .WithName("GetShape");

app.Run();

public record class Circle(double Radius);

public record class Rectangle(double Width, double Height);

public record class Triangle(double Base, double Height);

public union Shape(Circle, Rectangle, Triangle);
With the union exposed, an endpoint that returns a union is described with an anyOf schema listing each case type. Here is the OpenAPI document.
{
  "paths": {
    "/shapes/{id}": {
      "get": {
        "operationId": "GetShape",
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/Shape" }
              }
            }
          },
          "404": { "description": "Not Found" }
        }
      }
    }
  },
  "components": {
    "schemas": {
      // The union is an "anyOf" over its case types.
      "Shape": {
        "type": "object",
        "anyOf": [
          { "$ref": "#/components/schemas/Circle" },
          { "$ref": "#/components/schemas/Rectangle" },
          { "$ref": "#/components/schemas/Triangle" }
        ]
      },
      // Each case reuses its own standalone component, no "$type" discriminator.
      "Circle": {
        "type": "object",
        "required": [ "radius" ],
        "properties": { 
"radius": { "type": "number", "format": "double" } } }, "Rectangle": { "type": "object", "required": [ "width", "height" ], "properties": { "width": { "type": "number", "format": "double" }, "height": { "type": "number", "format": "double" } } }, "Triangle": { "type": "object", "required": [ "base", "height" ], "properties": { "base": { "type": "number", "format": "double" }, "height": { "type": "number", "format": "double" } } } } } }
Note that unlike polymorphic types, union cases don't carry a $type discriminator.

When you run this, you can see something like this:
Union Types in ASP.NET Core
A few limits apply in this preview. Only JSON request bodies and responses are supported. Binding a union from the query string, route values, headers, or form fields is not yet available (dotnet/aspnetcore #66648).

More read:

Hope this helps.

Happy Coding.

Regards,
Jaliya

Tuesday, July 21, 2026

C# 15: Brand New Union Types

In this post, let's have a look at Union types in C# and a subtle difference you will notice when you migrate from a closed class hierarchy to a union.

Some time ago I blogged about C# 15.0: Closed Class Hierarchies. There we used the closed keyword to model a fixed set of Shape types and let the compiler enforce exhaustive pattern matching. 

C# 15.0 also introduces union types, which solve a very similar problem: a value that must be exactly one of a fixed set of types, with exhaustiveness checked by the compiler.

I am using .NET 11 Preview 6 (latest as of today, it will change) for this post.

You will also want to set the following in your project file to opt into the latest language features.
<LangVersion>preview</LangVersion>
Let's start with where we left off, the closed hierarchy version.
Shape[] shapes =
[
    new Circle(2),
    new Rectangle(3, 4),
    new Triangle(4, 5),
];

foreach (Shape shape in shapes)
{
    Console.WriteLine($"{shape.GetType().Name}: {Area(shape):0.00}");
}

static double Area(Shape shape) => shape switch
{
    Circle(var r) => Math.PI * r * r,
    Rectangle(var w, var h) => w * h,
    Triangle(var b, var h) => 0.5 * b * h,
};

public closed record class Shape;

public record class Circle(double Radius) : Shape;

public record class Rectangle(double Width, double Height) : Shape;

public record class Triangle(double Base, double Height) : Shape;
And the output.
Circle: 12.57
Rectangle: 12.00
Triangle: 10.00
Nothing surprising here. Each element in the array is really a Circle, a Rectangle or a Triangle that derives from the Shape base type, so shape.GetType().Name reports the concrete type.

Now let's rewrite this using a union. Notice that Circle, Rectangle and Triangle no longer inherit from anything, they are just plain records. The union declaration composes them into a closed set.
public record class Circle(double Radius);

public record class Rectangle(double Width, double Height);

public record class Triangle(double Base, double Height);

public union Shape(Circle, Rectangle, Triangle);
I didn't have to do any other changes, the array initializer, the foreach and the Area switch expression are all untouched, and everything still compiles. That works because an implicit union conversion exists from each case type to the union, so a Circle, Rectangle or Triangle is silently converted to a Shape

But have a look at the output.
Shape: 12.57
Shape: 12.00
Shape: 10.00
The areas are still correct, but GetType().Name now returns Shape for every element. Why?

When you declare a union, the compiler generates a struct that implements IUnion and stores the actual case value in an object? property named Value. So public union Shape(Circle, Rectangle, Triangle); becomes roughly equivalent to this.
[Union]
public struct Shape : IUnion
{
    public Shape(Circle value) => Value = value;
public Shape(Rectangle value) => Value = value;
public Shape(Triangle value) => Value = value; public object? Value { get; } }
So inside the foreach, shape is the generated Shape struct wrapping a case value, not the case value itself. Calling GetType() on it boxes the struct and reports Shape. The Circle, Rectangle or Triangle instance lives inside the Value property.

This is also why the Area switch expression keeps working without any changes. Pattern matching on a union is applied to Value, so the union is transparent to the patterns and Circle(var r), Rectangle(var w, var h) and Triangle(var b, var h) still match.

If you actually want the concrete case type name, reach through Value.
foreach (Shape shape in shapes)
{
    Console.WriteLine($"{shape.Value?.GetType().Name}: {Area(shape):0.00}");
}
And now we are back to the concrete names.
Circle: 12.57
Rectangle: 12.00
Triangle: 10.00
That is the key mental model difference between the two features. A closed class hierarchy is real inheritance, so the runtime identity is the derived type and GetType() sees it. A union is a generated struct over a closed set of case types, so the runtime identity is the union, and you get to the case value through Value (or through pattern matching, which does the unwrapping for you).

Hope this helps.

Happy Coding.

Regards,
Jaliya