Repository navigation
Closed
Closed
Copy link
Milestone
Description
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 {
//...
}Reacted by Sergey Shelest and Tigran Sardaryan
Activity
weitzhandler commentedon Jun 1, 2025
Can you try
roxtec-simsab commentedon Jun 3, 2025
@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:
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.
weitzhandler commentedon Jun 3, 2025
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
LTreetype to the client side at all, and just have a string typePathproperty in the DTO.ShelestSergey commentedon Jun 9, 2025
@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.
roxtec-simsab commentedon Jun 10, 2025
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)
weitzhandler commentedon Jun 11, 2025
@ShelestSergey
Why do you need an
LTreeproperty in your DTO, it should be astring. Your client shouldn't reference Npgsql at all or know about the existance of theLTreetype.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
Yep I wouldn't mind that either.
roji commentedon Oct 17, 2026
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.JsontreatsLTreeas an object and reads its publicNLevelproperty. 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 tostringorToString().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.PostgreSQLpackages:LTree.get_NLevel()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:Program.cs:Run with
dotnet run. It throwsInvalidOperationExceptionfromLTree.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 anLTreevalue and of theFoorecord shown in the discussion. Converting a standalone value tostringbefore serialization also works, but does not automatically handleLTreeproperties inside an object.No likely duplicate was found in the open or closed
dotnet/efcoreissues 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.roji commentedon Oct 18, 2026
Decision: we'll annotate the LTree type with
[JsonConverter(typeof(LTreeJsonConverter))]so it serializes automatically.Backport LTree System.Text.Json serialization to 9.0 (#4012)