Skip to content

Serializing an LTree value to a JSON string results in an exception #3538

Closed

Description

@roxtec-simsab

Hi, we are currently unable to use LTree objects in our DTOs due to an exception that occurs during JSON serialization. The expected behavior in my opinion is for the object to be converted to its string value.

Here is a minimal repro:

csproj file:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <RootNamespace>ltree_exception</RootNamespace>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
  </ItemGroup>

</Project>

Program.cs:

using System.Text.Json;
using Microsoft.EntityFrameworkCore;

LTree ltree = new LTree("a.b.c.d");
string json = JsonSerializer.Serialize(ltree);

Output:

Unhandled exception. System.InvalidOperationException: The 'NLevel' method is not supported because the query has switched to client-evaluation. This usually happens when the arguments to the method cannot be translated to server. Rewrite the query to avoid client evaluation of arguments so that method can be translated to server.
   at Microsoft.EntityFrameworkCore.LTree.get_NLevel()
   at NLevelGetter(Object)
   at System.Text.Json.Serialization.Metadata.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.WriteCore(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.Metadata.JsonTypeInfo`1.Serialize(Utf8JsonWriter writer, T& rootValue, Object rootValueBoxed)
   at System.Text.Json.JsonSerializer.WriteString[TValue](TValue& value, JsonTypeInfo`1 jsonTypeInfo)
   at System.Text.Json.JsonSerializer.Serialize[TValue](TValue value, JsonSerializerOptions options)
   at Program.<Main>$(String[] args) in /home/path/Program.cs:line 5

One way to get around this exception right now is to create a custom JSON converter and apply it to a JsonSerializerOptions object that you then pass to the serialization:

// Program.cs
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.EntityFrameworkCore;

var options = new JsonSerializerOptions();
options.Converters.Add(new LtreeJsonConverter());

LTree lTree = new LTree("a.b.c.d.e");
string json = JsonSerializer.Serialize(lTree, options);
System.Console.WriteLine(json);

public class LtreeJsonConverter : JsonConverter<LTree>
{
    public override LTree Read(
        ref Utf8JsonReader reader,
        Type typeToConvert,
        JsonSerializerOptions options
    ) => new(reader.GetString() ?? "");

    public override void Write(
        Utf8JsonWriter writer,
        LTree value,
        JsonSerializerOptions options
    ) => writer.WriteStringValue(value.ToString());
}

I believe that this could be fixed for everyone by registering the JSON converter on the struct like this:

[JsonConverter(typeof(LtreeJsonConverter))]
public struct LTree {
//...
}

Activity

  1. weitzhandler commented on Jun 1, 2025

    @weitzhandler

    Can you try

    LTree ltree = new LTree("a.b.c.d");
    string json = ltree;
  2. roxtec-simsab commented on Jun 3, 2025

    @roxtec-simsab
    Author

    @weitzhandler Hi! Yes, that works of course due to the implicit string operators, but the example i showed above was just minimal code needed to reproduce the problem. What I'm most concerned about is when an LTree value is used in a class. I've run into cases where I have a data model with an LTree value that I want to send from an ASP.NET controller and a separate DTO model isn't warranted.

    These classes for instance can't be serialized without registering a custom serializer:

    record Foo(LTree LTree, string Name);
    
    class Node
    {
        public Guid Id { get; set; }
        public string Description { get; set; }
        public LTree Path { get; set; }
    }

    I think applying the JsonConverter globally should be fine because the only visible property is NLevel which isn't even accessible in client code anyway.

  3. weitzhandler commented on Jun 3, 2025

    @weitzhandler

    If I guessed right the DTO is meant for the client that's not having any interaction with the DB, if that's the case, you don't have to disclose the LTree type to the client side at all, and just have a string type Path property in the DTO.

  4. ShelestSergey commented on Jun 9, 2025

    @ShelestSergey

    @weitzhandler,
    I can explain my case:
    I receve this error when using Swashbuckle Swagger. When method in controller:
    return Ok(result);
    In Swagger interface I receive 500 Error.
    Why I have to put LTree attribute in Model and pass to Client...
    DTO: with LTree attribute scaffolded from DB. LTree field is "NOT NULL" in table. It processes in trigger after insert or update on field parentid.
    Model without it.
    If I want to take changes in existing record, first I took it from DB, Adapt to Model, make changes and then Adapt to DTO record.
    If I exclude attribute, after changing Model object and adapting it in DTO, I will receive an error "null-violate constraint" if I changed something but parentid.
    First workaround is to exclude parentid check in update trigger. But it will fire everytime I change record in table.
    Maybe I'm doing something completely wrong :)
    Although, I think that's not correct behavior to receive 500 error in swashbuckle.
    I hope, my explanation was clear enough.

  5. roxtec-simsab commented on Jun 10, 2025

    @roxtec-simsab
    Author

    If I guessed right the DTO is meant for the client that's not having any interaction with the DB, if that's the case, you don't have to disclose the LTree type to the client side at all, and just have a string type Path property in the DTO.

    What I meant was that in that situation a DTO wasn't required, but because LTrees can't be serialized I would either be forced to use one or register a custom converter. I think either it should be documented that it is how you expect people to use LTrees, or it should be fixed by making the value able to be serialized (i showed how in the original issue text)

  6. weitzhandler commented on Jun 11, 2025

    @weitzhandler

    @ShelestSergey

    DTO: with LTree attribute scaffolded from DB. LTree field is "NOT NULL" in table. It processes in trigger after insert or update on field parentid.

    Why do you need an LTree property in your DTO, it should be a string. Your client shouldn't reference Npgsql at all or know about the existance of the LTree type.

    If I exclude attribute, after changing Model object and adapting it in DTO, I will receive an error "null-violate constraint" if I changed something but parentid.

    Really it's the solely the server's responsibility to assign the paths. The client should just consume them. Depending of the type of parentid, it should be a value type that can have a default value (i.e. default(int), if the server is going to pick up and assign those values when adding and saving the data.

    @roxtec-simsab

    or it should be fixed by making the value able to be serialized (i showed how in the original issue text)

    Yep I wouldn't mind that either.

  7. added theissue type on Oct 17, 2026
  8. roji commented on Oct 17, 2026

    @roji
    Member

    AI Triage

    The below is an AI-generated analysis and may contain inaccuracies.

    Confirmed; classified as a bug. The original standalone example reproduces without a DbContext, database, ASP.NET, or Swagger.

    Cause and scope

    System.Text.Json treats LTree as an object and reads its public NLevel property. That getter intentionally throws outside a translated query; see the LTree implementation in 9.0.4. The serializer does not automatically use the implicit conversion to string or ToString().

    The exception's reference to a query switching to client evaluation is misleading in this case: no query runs. This concerns the JSON serialization contract of the Npgsql-specific CLR type, not SQL translation or database behavior. Switching to SQL Server or SQLite is not an applicable comparison because the repro does not configure or invoke a database provider.

    Versions and regression assessment

    Executed the same repro against these Npgsql.EntityFrameworkCore.PostgreSQL packages:

    Package version Target framework Result
    8.0.0 net8.0 Throws from LTree.get_NLevel()
    8.0.11 net8.0 Same
    9.0.3 net8.0 Same
    9.0.4 net8.0 Same
    10.0.3 net10.0 Same
    11.0.0-rc.1.1 net11.0 Same

    This is not a regression introduced in 9.0.4: the preceding patch and older major version also fail. No working version was found among the releases tested, and upgrading to the latest stable or prerelease package tested does not resolve it.

    minimal repro

    LTreeRepro.csproj:

    <Project Sdk="Microsoft.NET.Sdk">
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net8.0</TargetFramework>
      </PropertyGroup>
      <ItemGroup>
        <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
      </ItemGroup>
    </Project>

    Program.cs:

    using System.Text.Json;
    using Microsoft.EntityFrameworkCore;
    
    LTree ltree = new LTree("a.b.c.d");
    string json = JsonSerializer.Serialize(ltree);

    Run with dotnet run. It throws InvalidOperationException from LTree.get_NLevel() instead of producing the desired JSON string "a.b.c.d".

    Workaround and related issues

    Confirmed that the reporter's registered JsonConverter<LTree> allows serialization and deserialization both of an LTree value and of the Foo record shown in the discussion. Converting a standalone value to string before serialization also works, but does not automatically handle LTree properties inside an object.

    No likely duplicate was found in the open or closed dotnet/efcore issues searched. Related provider issues #2330 and #3610 explain why client-side implementations of tree operations are out of scope; neither addresses JSON serialization. A built-in string JSON converter would address this report without requiring client-side implementations of those operations.

  9. roji commented on Oct 18, 2026

    @roji
    Member

    Decision: we'll annotate the LTree type with [JsonConverter(typeof(LTreeJsonConverter))] so it serializes automatically.

  10. added this to the 10.0.4 milestone on Oct 18, 2026
  11. self-assigned this
    on Oct 18, 2026
  12. added a commit that references this issue on Oct 18, 2026
    21572e6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions