Tuesday, September 30, 2025

EF Core 10.0: Support for JSON Data Type in Microsoft SQL Server

From Microsoft SQL Server 2025 (17.x) which is already available in Preview, we now have a new Data Type: json

EF Core 10.0 now fully supports the json data type.

Consider the following Model.

public class Customer
{
    public int Id { getset}

    public string Name { getset}

    public required Contact Contact { getset}
}

public class Contact
{
    public required Address Address { getset}

    public List<PhoneNumber> PhoneNumbers { getset} = [];
}

public class Address
{
    public required string Street { getset}

    public required string City { getset}

    public required string State { getset}

    public required string PostalCode { getset}
}

public class PhoneNumber
{
    public PhoneNumberType Type { getset}

    public string Number { getset}

    public PhoneNumber(PhoneNumberType typestring number)
    {
        Type = type;
        Number = number;
    }
}

public enum PhoneNumberType
{
    Mobile,
    Home
}

And I have configured the MyDbContext as follows.

public class MyDbContext : DbContext
{
    public DbSet<Customer> Customers { getset}

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder
            .UseSqlServer("<SqlServer2025_ConnectionString>"x =>
            {
                x.UseCompatibilityLevel(170);
            });
    }

    override protected void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder
            .Entity<Customer>(x =>
            {
                x.ComplexProperty(x => x.Contact, x => x.ToJson());
            });
    }
}

Note the ComplexProperty(). For more information on ComplexProperty(), read a previous post: EF Core 10.0: Support for Complex Types without using Owned Entities for more information.

When configured to target Microsoft SQL Server 2025, EF Core 10.0 creates the following table for the above.

CREATE TABLE [Customers] (
    [Id] int NOT NULL IDENTITY,
    [Name] nvarchar(max) NOT NULL,
    [Contact] json NOT NULL,
    CONSTRAINT [PK_Customers] PRIMARY KEY ([Id])
);
Data Type: json

Querying

We can do queries on JSON data, for example, consider the following.

List<Customer> customersInWA = await context.Customers
    .Where(x => x.Contact.Address.State == "WA")
    .ToListAsync();

The generated SQL statements will be as follows.

SELECT [c].[Id], [c].[Name], [c].[Contact]
FROM [Customers] AS [c]
WHERE JSON_VALUE([c].[Contact], '$.Address.State' RETURNING nvarchar(max)) = N'WA'

Projection

List<string> distinctStates = await context.Customers
    .Select(x => x.Contact.Address.State)
    .Distinct()
    .ToListAsync();

The generated SQL statement:

SELECT DISTINCT JSON_VALUE([c].[Contact], '$.Address.State' RETURNING nvarchar(max))
FROM [Customers] AS [c]

Update

Customer customerToUpdate = await context.Customers.SingleAsync(x => x.Name == "Jane Doe");
customerToUpdate.Contact.Address.PostalCode = "97202";
await context.SaveChangesAsync();

Here the generated SQL statement:

SET IMPLICIT_TRANSACTIONS OFF;
SET NOCOUNT ON;
UPDATE [Customers] SET [Contact] = @p0
OUTPUT 1
WHERE [Id] = @p1;

However, I'd expect it be something like below:

SET IMPLICIT_TRANSACTIONS OFF;
SET NOCOUNT ON;
UPDATE [Customers] SET [Contact] = JSON_MODIFY([Contact], 'strict $.Address.PostalCode', JSON_VALUE(@p0, '$[0]'))
OUTPUT 1
WHERE [Id] = @p1;

Created an issue: dotnet/efcore/issues/36732

It's getting nicer and exciting everyday.

Read more:
   What's New in EF Core 10

Happy Coding.

Regards,
Jaliya

Thursday, September 11, 2025

EF Core 10.0: Support for Complex Types without using Owned Entities

EF Core 10.0 introduces a new approach for mapping complex types in a Entity. Prior to EF Core 10.0, we can manage complex types using Owned Entities.

With EF Core 10.0, we now have a new method ComplexProperty() and in this post let's have a look at the newer approach and possibly do a comparison.

Consider the following.

public class Customer
{
    public int Id { getset}

    public string Name { getset}

    public required Address ShippingAddress { getset}

    public required Address BillingAddress { getset}
}

public class Address
{
    public required string Street { getset}

    public required string City { getset}

    public required string State { getset}

    public required string PostalCode { getset}
}

Now let's see how we can map ShippingAddress and BillingAddress, using Owned Entities vs ComplexProperty.

public class MyDbContext : DbContext
{
    public DbSet<Customer> Customers { getset}

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder
            .UseSqlServer("<ConnectionString>");
    }

    override protected void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder
            .Entity<Customer>(x =>
            {
                // Using Owned Entity Types
                x.OwnsOne(x => x.ShippingAddress);

                // Using Complex Types (new in EF Core 10)
                x.ComplexProperty(x => x.BillingAddress);
            });
    }
}

Owned Entity vs ComplexProperty
You can basically do all the customizations as we used to do in Owned Entities. 

For an example, map the properties to different column names, I can do this.

override protected void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder
        .Entity<Customer>(x =>
        {
            // Using Owned Entity Types
            x.OwnsOne(x => x.ShippingAddress, y =>
            {
                // Map the properties to different column names
                y.Property(p => p.Street).HasColumnName("ShippingStreet");
            });

            // Using Complex Types(new in EF Core 10)
            x.ComplexProperty(x => x.BillingAddress, y =>
            {
                // Map the properties to different column names
                y.Property(p => p.Street).HasColumnName("BillingStreet");
            });
        });
}

From EF Core 10.0 onwards, ComplexProperty() would be more recommended approach for managing complex types.

Read more:
   EF Core 10.0: Complex Types

Hope this helps.

Happy Coding.

Regards,
Jaliya

Wednesday, September 10, 2025

Announcing Visual Studio 2026: Insiders

Just a few hours ago, the first Public Preview of the next version of Visual Studio is announced along with .NET 10 RC 1. It's Visual Studio 2026 or Visual Studio 18 under the classic versioning system. 
Visual Studio 2026: Insiders
This new release brings significant performance improvements and of course a host of exciting new features.

One of the standout updates is the introduction of the Insiders channel, which replaces the traditional Preview channel from earlier versions of Visual Studio.

There's a lot to explore, and it's available now. Try it out today!


Happy Coding.

Regards,
Jaliya

Thursday, September 4, 2025

ASP.NET Core 10.0: Custom Validation Support for Minimal APIs

In a previous post, I wrote about ASP.NET Core 10.0: Validation Support for Minimal APIs. In this post, let's go a bit further and see how we can implement custom validations using both ValidationAttribute implementations and implementing the IValidatableObject interface.

ValidationAttribute 


With ValidationAttribute, we can create a Custom attribute with our own custom logic.
public class CustomEmptyValidationAttribute : ValidationAttribute
{
    protected override ValidationResultIsValid(objectvalueValidationContext _)
    {
        if (value is string str && string.IsNullOrEmpty(str))
        {
            return new ValidationResult("Value cannot be null or empty.");
        }

        return ValidationResult.Success;
    }
}
And then we can apply the attribute, something like below for an example.
internal record Employee([CustomEmptyValidation] string Name);

IValidatableObject 


A class/record can implement IValidatableObject and add the validation logic. The validation will kick in as part of model binding.
internal record Employee : IValidatableObject
{
    [Range(1, int.MaxValue)]
    public int Id { getset}

    public string Name { getset}

    public IEnumerable<ValidationResult> Validate(ValidationContext _)
    {
        if (string.IsNullOrEmpty(Name))
        {
            yield return new ValidationResult("Name cannot be null or empty."[nameof(Name)]);
        }
    }
}
Note: Currently there is a bug where IValidatableObject wouldn't trigger validation when there is no validation attribute on a property. (aspnetcore/issues/63394: ASP.NET Core 10.0: Built-in Validation with IValidatableObject)

Hope this helps.

Happy Coding.

Regards,
Jaliya

Saturday, August 30, 2025

ASP.NET Core 10.0: Validation Support for Minimal APIs

With ASP.NET Core 10.0, we now have built in validation support for Minimal APIs for request data in following.
  • Route parameters, Query Strings
  • Header
  • Request body
If any validation fails, the runtime returns a 400 Bad Request response with details of the validation errors.

Validations are defined using attributes in the System.ComponentModel.DataAnnotations namespace. We can even create our own validators using,
To register validation services and enable validation, we need to call the following method in the Program.cs.
builder.Services.AddValidation();
Now we can do something like below to validate route parameters.
app.MapGet("/employees/{employeeId}"([Range(1, int.MaxValue)] int employeeId) =>
{
    // Omitted
});
And if we try the endpoint with an incorrect route parameter, we will get an validation error.
GET {{WebApplication1_HostAddress}}/employees/0
Accept: application/json
Route parameter validation
We can use the similar concept with record types as well.

Say I have the following Employee record that has a annotated property.
internal record Employee([Required] string Name);
And now If I try to make a request to the following endpoint,
app.MapPost("/employees"(Employee employee) =>
{
    // Omitted
});
With a empty value for name,
POST {{WebApplication1_HostAddress}}/employees
Content-Type: application/json
{
    "name": ""
}
I am getting the following 400 Bad Request.
Request Body Validation
You can disable the validation at the endpoint by calling DisableValidation(), something like below:
app.MapPost("/employees"(Employee employee) =>
    {
        // Omitted
    })
    .DisableValidation();
Hope this helps.

Happy Coding.

Regards,
Jaliya

Wednesday, August 27, 2025

Azure Logic Apps (Consumption): HTTP Action to POST multipart/form-data with Files and Fields

In this post, let's see how we can POST multipart/form-data with files and fields using a HTTP action in a Consumption Azure Logic App.

I have the following Test API which I am going to call from the Logic App.
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

WebApplication app = builder.Build();

app.UseHttpsRedirection();

app.MapPost("/api/Files"async (IFormCollection formCollection) =>
{
    IFormFilefile = formCollection.Files.SingleOrDefault();

    if (file == null || file.Length == 0)
    {
        return Results.BadRequest("No file uploaded.");
    }

    string fileName = file.FileName;
// Save file and ensure file is good
    string filePath = Path.Combine(@"<some-location>"fileName);
    using FileStream stream = File.Create(filePath);
    await file.CopyToAsync(stream);

    return Results.Ok(new
    {
        fileName,
        fileSize = file.Length,
        someField = formCollection["someField"].ToString()
    });
})
.DisableAntiforgery();

app.Run();
In my Logic App, I have a variable called file  of type object and it's populated with data. 
{
  "fileName""<OMITTED>", // some-file.pdf
  "base64Content""<OMITTED>", // Base 64 encoded content
  "contentType""<OMITTED>" // application/pdf
}
And now let's add the HTTP action as follows:
HTTP Action
Code for Body is below.
{
  "$content-type""multipart/form-data",
  "$multipart": [
    {
      "headers": {
        "Content-Disposition""form-data; name=\"file\"; filename=\"@{variables('file')?['fileName']}\""
      },
      "body": {
        "$content""@{variables('file')?['base64Content']}",
        "$content-type""@{variables('file')?['contentType']}"
      }
    },
    {
      "headers": {
        "Content-Disposition""form-data; name=\"someField\""
      },
      "body""Hello World!"
    }
  ]
}
And now when the HTTP action is executed, I can see the values are getting passed correctly.
API Endpoint
Hope this helps.

Happy Coding.

Regards,
Jaliya

Wednesday, August 20, 2025

Azure Functions HTTP Orchestration Trigger with multipart/form-data

In this post, let's see have how we can invoke a HTTP Orchestration Trigger in an Azure Durable Functions with multipart/form-data. There can be scenarios where you want to pass multipart/form-data (mostly files) to HTTP Orchestration Trigger.

Note I am using Azure Functions Isolated model.

If you scaffold a a Durable Function in Visual Studio, you will see it's HTTP Trigger function to be something like below.
[Function("Function_HttpStart")]
public static async Task<HttpResponseData> HttpStart(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get""post")] HttpRequestData req,
    [DurableClient] DurableTaskClient client,
    FunctionContext executionContext)
{
    string instanceId = await client.ScheduleNewOrchestrationInstanceAsync(nameof(Function));
        
    // Omitted for brevity.
        
    return await client.CreateCheckStatusResponseAsync(reqinstanceId);
}
Notice that it uses HttpRequestData for request and for HttpResponseData. which is available via,
Microsoft.Azure.Functions.Worker.Extensions.Http
Instead of these, we can make use of Azure Functions ASP.NET Core integration and start using ASP.NET Core Request/Response types including HttpRequestHttpResponse and IActionResult in HTTP Triggers.

Azure Functions ASP.NET Core integration is available via following NuGet package.
Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore
And then in the Program.cs,
FunctionsApplicationBuilder builder = FunctionsApplication.CreateBuilder(args);

// Enable ASP.NET Core features in Azure Functions
builder.ConfigureFunctionsWebApplication();
// Omitted for brevity
And now we can change the HTTP trigger as follows.
[Function("Function_HttpStart")]
public static async Task<IActionResult> HttpStart(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get""post")] HttpRequest req,
    [DurableClient] DurableTaskClient client,
    FunctionContext executionContext)
{
    string instanceId = await client.ScheduleNewOrchestrationInstanceAsync(nameof(Function));

    if (req.HasFormContentType)
    {
        IFormCollection formCollection = await req.ReadFormAsync();
        // TODO: Process form data as needed.
    }

    // Omitted for brevity.

    HttpManagementPayload httpManagementPayload = client.CreateHttpManagementPayload(instanceId);
    return new ObjectResult(httpManagementPayload)
    {
        StatusCode = (int)HttpStatusCode.Accepted
    };
}
By the way, if you want to use multipart/form-data in any of the Azure Functions HTTP Triggers, Azure Functions ASP.NET Core integration is the way. 

Hope this helps.

Happy Coding.

Regards,
Jaliya

Saturday, August 9, 2025

Azure Automation Runbooks and Azure Cosmos DB for MongoDB

I recently wanted to run a daily job on an Azure Cosmos DB for MongoDB. I thought Logic Apps would be a good fit, but surprisingly there is still a no connector that supports Azure Cosmos DB for MongoDB (currently only supports Azure Cosmos DB for NoSQL), and that's a bummer.

But there are of course other approaches we can take, like Azure Automation Runbooks. 

In this post, let's see how we can create an Azure Automation Python Runbook to query Azure Cosmos DB for MongoDB.

I have an Azure Automation account created and I have created a Python 3.10 Runbook. Now in order to connect to MongoDB, I am going to use pymongo package. 

First let's add the package to Automation Account. Note: For Python 3.10 packages, only .whl files targeting cp310 Linux OS are currently supported.

I am downloading the pymongo package to my local computer.

pip download pymongo `
    --platform manylinux2014_x86_64 `
    --only-binary=:all: `
    --python-version 3.10

Upon completion of above command, I can see 2 .whl files, pymongo and a dependency.

.whl files
Then I am uploading both these .whl files to Python packages under Automation Account.

Add Python packages

Now I can run some python code to query my Azure Cosmos DB for MongoDB.

from pymongo import MongoClient

MONGODB_CONNECTIONSTRING = "mongodb://..."
DATABASE_NAME = "<Database_Name>"
COLLECTION_NAME = "<Collection_Name>"

client = MongoClient(MONGODB_CONNECTIONSTRING, ssl=True)
db = client[DATABASE_NAME]
collection = db[COLLECTION_NAME]

documents = collection.find(
    {
        # query to filter documents
    })

documents = list(documents)

client.close()
# TODO: Work with documents

Hope this helps.

Happy Coding.

Regards,
Jaliya

Wednesday, July 23, 2025

.NET Isolated Azure Durable Functions: Distributed Tracing

In this post, let's have a look at the power of Distributed Tracing in .NET Isolated Azure Durable Functions. This is one of the new features that got GA like few weeks ago.

First let's have a look at a simple Durable Function and see how it's logged in Application Insights.
public static class Function
{
    [Function(nameof(HttpStart))]
    public static async Task<HttpResponseData> HttpStart(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get")] HttpRequestData req,
        [DurableClient] DurableTaskClient client,
        FunctionContext executionContext)
    {
        string instanceId =
            await client.ScheduleNewOrchestrationInstanceAsync(nameof(RunOrchestrator));

        return await client.CreateCheckStatusResponseAsync(reqinstanceId);
    }

    [Function(nameof(RunOrchestrator))]
    public static async Task<List<string>> RunOrchestrator(
        [OrchestrationTrigger] TaskOrchestrationContext context)
    {
        EntityInstanceId entityId = new(nameof(HelloHistoryEntity)"helloHistory");

        await context.Entities.CallEntityAsync<string>(entityId,
            nameof(HelloHistoryEntity.Reset));

        string result = await context.CallActivityAsync<string>(nameof(SayHello)"Tokyo");
        await context.Entities.CallEntityAsync<string>(entityId,
            nameof(HelloHistoryEntity.Add),
            result);

        result = await context.CallActivityAsync<string>(nameof(SayHello)"Seattle");
        await context.Entities.CallEntityAsync<string>(entityId,
            nameof(HelloHistoryEntity.Add),
            result);

        result = await context.CallActivityAsync<string>(nameof(SayHello)"London");
        await context.Entities.CallEntityAsync<string>(entityId,
            nameof(HelloHistoryEntity.Add),
            result);

        List<string> outputs = await context.Entities.CallEntityAsync<List<string>>(entityId,
            nameof(HelloHistoryEntity.Get));
        return outputs;
    }

    [Function(nameof(SayHello))]
    public static string SayHello([ActivityTrigger] string nameFunctionContext executionContext)
    {
        return $"Hello {name}!";
    }
}

public class HelloHistoryEntity : TaskEntity<List<string>>
{
    public void Add(string message) => State.Add(message);

    public void Reset() => State = [];

    public List<string> Get() => State;

    [Function(nameof(HelloHistoryEntity))]
    public Task RunEntityAsync([EntityTrigger] TaskEntityDispatcher dispatcher)
    {
        return dispatcher.DispatchAsync(this);
    }
}
Here I have a single Orchestrator that gets triggered by a HTTP function, and the Orchestrator calls an Activity and a Entity few times.

Once I trigger the HTTP function, the logs for HTTP Request looks like below.
Without Distributed Tracing
And this isn't quite helpful.

Now let's enable Distributed Tracing. For .NET Isolated Durable Functions, Distributed Tracing V2 is supported with Microsoft.Azure.Functions.Worker.Extensions.DurableTask >= v1.4.0. Make sure to update your packages before doing the next step.

Now modify the host.json as follows.
{
  "version""2.0",
  "extensions": {
    "durableTask": {
      "tracing": {
        "distributedTracingEnabled"true,
        "version""V2"
      }
    }
  }
}
And that's about it.

Now if I I trigger the HTTP function, the logs for HTTP Request looks like below.
Distributed Tracing
Now we can see the full execution, the call to the Orchestrator and all related Activity and Entity calls.

Isn't it just nice.

Happy Coding.

Regards,
Jaliya