Skip to content

LTree functions without database queries #2330

Closed

Description

@Undertakerrip

Is there an option using LTree properties for comparison without usage of the data context?

Here is a short example (.NET 6 REST API):

Section modal:

public class Section
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public int? ParentSectionId { get; set; }
    public Section ParentSection { get; set; }
    public LTree? Path { get; set; }
}

Database context:

public class DataContext : DbContext
{
    public DbSet<Section> Sections { get; set; }

    public DataContext(DbContextOptions options) : base(options) { }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.HasPostgresExtension("ltree");
        modelBuilder.Entity<Section>()
            .HasIndex(m => m.Path)
            .HasMethod("gist");
    }
}

Orm initialization in service configuration:

builder.Services.AddDbContext<DataContext>(options => options.UseNpgsql(builder.Configuration.GetConnectionString("dbConnectionString")));

There are two sections, one with id 2 (LTree path is 2) and the other with id 3 (LTree path is 2.3).

This call works:

Section parentSection = (await _dataContext.Sections.FindAsync(parentId)) ?? throw new Exception("Not found");
Section foundSection = _dataContext.Sections.FirstOrDefault(l => l.Path.Value.IsDescendantOf(parentSection.Path.Value));
return foundSection.Id;

And finally the failing call:

[HttpGet]
[Route("{sectionId}/{parentId}")]
public async Task<bool> IsDescendantOf(int sectionId, int parentId)
{
    Section section = (await _dataContext.Sections.FindAsync(sectionId)) ?? throw new Exception("Not found");
    Section parentSection = (await _dataContext.Sections.FindAsync(parentId)) ?? throw new Exception("Not found");
    return section.Path.Value.IsDescendantOf(parentSection.Path.Value);
}

This call results in:

System.InvalidOperationException: The 'IsDescendantOf' 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.IsDescendantOf(LTree other)
   at NpgSqlESampe.Controllers.SectionController.IsDescant(Int32 sectionId, Int32 parentId) in C:\Users\user\source\repos\NpgSqlESampe\Controllers\SectionController.cs:line 52
   at lambda_method79(Closure , Object )
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Apparently there is a translation for PostreSQL in v6 (according to the Npgsql translations ) but there is no possibility to use these funtions without the database context. Ist that correct? And if yes: Any chances to provide this?

This example is not representative, but we use the LTree for checks like movements only within the same tree and we don't want to make a database call only for a true/false, if we need both sections anyway in that situation.

Activity

  1. roji commented on Apr 15, 2022

    @roji
    Member

    Allowing you to run IsDescendantOf as above - not in an EF LINQ query - would mean providing a full .NET implementation that duplicates the PostgreSQL LTree functionality; this isn't something we can do, since it ultimately means reimplementing all PostgreSQL functions in .NET, which obviously isn't feasible.

    However, note that the above already (potentially) does two database roundtrips - one for each FindAsync. You should be able to replace that with a single query that performs IsDescendantOf over the two rows, given sectionId and parentId; that would be more efficient than the current code above.

    Let me know if i've misunderstood your question or if you're looking for smoething else.

  2. Undertakerrip commented on Apr 15, 2022

    @Undertakerrip
    Author

    Thank you for your answer. You are right. If the scenrio would be that simple, it could be easily handled in one query like: FirstOrDefault(x => x.Id == id && x.isAncesterOf(section)) or something like that. But if there is no result, we could not be sure why (id not not found or not an ancestor). But as I said, that was only a short and easy to explain example.

    The main information is, that there is unfortunately no option to support LTree. Thanks for clarification.
    The ticket can thus be closed.

    Addition: There is a typo in the translation documentation:

    ltrees.FirstOrDefault(l => l.IsDescendant(ltree))

    and

    ltree1.IsDescendant(ltree2)

    should be:

    ltrees.FirstOrDefault(l => l.IsDescendantOf(ltree))

    and

    ltree1.IsDescendantOf(ltree2)

  3. roji commented on Apr 15, 2022

    @roji
    Member

    But if there is no result, we could not be sure why (id not not found or not an ancestor).

    That's pretty easy to do: you can project the result of IsAncestorOf out of database (rather than filtering by it), so you'd know to distinguish between the different possibilities.

    Addition: There is a typo in the translation documentation:

    Thanks, fixing these via npgsql/doc#198.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions