Skip to content

Projections on JSON columns containing array are not working #34367

Closed as not planned

Description

@IvanFeric

I'm working on a project where I have a table containing a JSON column containing an array of objects. I'm trying to construct a query that returns data from this table where values from the column are projected to a different, DTO class that I'm returning from the API.

Here's the data model I'm using:

public sealed class Client
{
  public Guid Id { get; set; }
  public DateTimeOffset CreatedAt { get; set; }
  public required string Name { get; set; }
  public required List<Contact> Contacts { get; set; } = [];
}

public sealed class Contact
{
  public required string FirstName { get; set; }
  public required string LastName { get; set; }
  public string? Address { get; set; }
  public string? Email { get; set; }
  public string? PhoneNumber { get; set; }
  public string? Notes { get; set; }
}

The data model is configured with this configuration:

public sealed class ClientConfiguration : IEntityTypeConfiguration<Client>
{
  public void Configure(EntityTypeBuilder<Client> builder)
  {
    builder.ToTable("Clients");
    builder.HasKey(c => c.Id);

    builder.OwnsMany(c => c.Contacts, contactsBuilder => contactsBuilder.ToJson());
  }
}

The DTO classes used during projection are the following:

public class ClientDto
{
  public Guid Id { get; set; }

  [JsonRequired]
  public string Name { get; set; } = null!;

  public List<ContactDto> Contacts { get; set; } = [];

  [JsonIgnore]
  public string? PhoneNumber => Contacts?.FirstOrDefault(c => !string.IsNullOrEmpty(c.PhoneNumber))?.PhoneNumber;

  [JsonIgnore]
  public string? Email => Contacts?.FirstOrDefault(c => !string.IsNullOrEmpty(c.Email))?.Email;
}

public class ContactDto
{
  [JsonRequired]
  public string FirstName { get; set; } = null!;
  [JsonRequired]
  public string LastName { get; set; } = null!;
  public string? Address { get; set; }
  public string? Email { get; set; }
  public string? PhoneNumber { get; set; }
  public string? Notes { get; set; }
}

I'm using the following query from the method GetClients to get the projected data from the database:

public class ClientService(DbContext dbContext) : IClientService
{
  private DbContext Context { get; } = dbContext;

  private IQueryable<Client> Clients => Context.Set<Client>();

  public async Task<List<ClientDto>> GetClients(CancellationToken cancellationToken)
    => await Clients.AsDto().AsNoTracking().ToListAsync(cancellationToken);
}

The method AsDto() is an extension method that looks like this:

  public static IQueryable<ClientDto> AsDto(this IQueryable<Client> clients)
    => clients.Select(c => new ClientDto
    {
      Id = c.Id,
      Name = c.Name,
      Contacts = c.Contacts.Select(contact => new ContactDto
      {
        FirstName = contact.FirstName,
        LastName = contact.LastName,
        Address = contact.Address,
        Email = contact.Email,
        PhoneNumber = contact.PhoneNumber
      }).ToList()
    });

I'm using a dev environment running SQL Server and unit tests configured to use Sqlite. When running this code in a dev environment, I get the correct data from the database. However, when I try to test using Sqlite, I'm getting the following exception:

Message: 
System.InvalidOperationException : Translating this query requires the SQL APPLY operation, which is not supported on SQLite.

  Stack Trace: 
ApplyValidatingVisitor.VisitExtension(Expression extensionExpression)
ApplyValidatingVisitor.VisitExtension(Expression extensionExpression)
SqliteQueryTranslationPostprocessor.Process(Expression query)
QueryCompilationContext.CreateQueryExecutor[TResult](Expression query)
Database.CompileQuery[TResult](Expression query, Boolean async)
QueryCompiler.CompileQueryCore[TResult](IDatabase database, Expression query, IModel model, Boolean async)
<>c__DisplayClass12_0`1.<ExecuteAsync>b__0()
CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
QueryCompiler.ExecuteAsync[TResult](Expression query, CancellationToken cancellationToken)
EntityQueryProvider.ExecuteAsync[TResult](Expression expression, CancellationToken cancellationToken)
EntityQueryable`1.GetAsyncEnumerator(CancellationToken cancellationToken)
ConfiguredCancelableAsyncEnumerable`1.GetAsyncEnumerator()
EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
ClientService.GetClients(Paging paging, CancellationToken cancellationToken) line 12
ClientServiceTest.GetClients_ReturnsClients() line 82
--- End of stack trace from previous location ---

The test looks like this:

private Guid FirstClient { get; } = Guid.NewGuid();
private Guid SecondClient { get; } = Guid.NewGuid();

public async Task GetClients_ReturnsOnlyClientsOfTheFirm()
{
  using var connection = new SqliteConnection("Filename=:memory:");
  connection.Open();

  var contextOptions = new DbContextOptionsBuilder<DbContext>()
    .UseSqlite(Connection)
    .Options;

  var context = new DbContext(contextOptions);
  context.Database.EnsureCreated();
  context.AddRange([
  new Client
  {
    Id = FirstClient,
    Name = "F1r$+",
    Contacts =
    [
      new()
      {
        FirstName = "F1r$+",
        LastName = "14$+",
        Email = "[email protected]",
        PhoneNumber = "1234567890"
      },
      new()
      {
        FirstName = "0+h3r",
        LastName = "14$+2",
        Email = "[email protected]",
        PhoneNumber = "0123456789"
      }
    ]
  },
  new Client
  {
    Id = SecondClient,
    Name = "$3c0nd",
    Contacts =
    [
      new()
      {
        FirstName = "$3c0nd",
        LastName = "14$+"
      },
      new()
      {
        FirstName = "0+h3r",
        LastName = "14$+2",
        Email = "[email protected]",
        PhoneNumber = "0123456789"
      }
    ]
  }
]);
  await context.SaveChangesAsync();

  ClientService clientService = new(context);

  var result = await clientService.GetClients(new(1, 10), default);

  Assert.NotNull(result);
  Assert.Equal(2, result.Count);
  Assert.Contains(result, r => r.Id == FirstClient &&
    r.Name.Equals("F1r$+", StringComparison.Ordinal) &&
    r.Email!.Equals("[email protected]", StringComparison.Ordinal) &&
    r.PhoneNumber!.Equals("1234567890", StringComparison.Ordinal));
  Assert.Contains(result, r => r.Id == SecondClient && r.Name.Equals("$3c0nd", StringComparison.Ordinal) && r.Email == null && r.PhoneNumber == null);
}

In my test project, I'm using latest .NET 8 with the following Sqlite dependency:

<PackageVersion Include="Microsoft.EntityFrameworkCore.Sqlite" Version="8.0.7" />

I assume that this is a bug since a simple projection from one class to another without any filter should work in SqlLite for JSON array columns and that it shouldn't require any advanced transformations unsupported by Sqlite.

I'm aware that I could change my query to perform a transformation from data model to DTO after fetching the data from the database. However, I expect over time to have properties that I don't want to return as part of the DTO and I don't want to overfetch the unnecessary data from the database just to support my unit tests.

Activity

  1. roji commented on Aug 7, 2024

    @roji
    Member

    I assume that this is a bug since a simple projection from one class to another without any filter should work in SqlLite for JSON array columns and that it shouldn't require any advanced transformations unsupported by Sqlite.

    This can be understood better by examining the SQL produced by SQL Server for your query:

    SELECT [c].[Id], [c].[Name], JSON_VALUE([c0].[value], '$.FirstName'), JSON_VALUE([c0].[value], '$.LastName'), JSON_VALUE([c0].[value], '$.Address'), JSON_VALUE([c0].[value], '$.Email'), JSON_VALUE([c0].[value], '$.PhoneNumber'), [c0].[key]
    FROM [Clients] AS [c]
    OUTER APPLY OPENJSON([c].[Contacts], '$') AS [c0]
    ORDER BY [c].[Id], CAST([c0].[key] AS int)

    Unlike simple properties, EF generates an OUTER APPLY as the translation for your inner Select (the one over Contacts), and that's simply not supported by Sqlite.

    You can easily work around this by forcing the projection to be evaluated client-side by inserting AsEnumerable()/AsAsynvEnumerable() before your Select over Contacts - this is fine and has no drawbacks.

    Otherwise, this is a good illustration of the limitations of using a SQLite as a testing database system that's not the same as your production system (i.e. SQL Server). Consider writing tests against SQL Server instead - possibly using testcontainers.net to make this easier - this ensure that everything works the same way in your tests as in production (see our docs on this).

    Finally, in this particular case it should be possible for EF to transform the query, moving the CROSS APPLY to the projection instead. Opened #34375 to track this.

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions