1

I have a complex array and need to query in EF Core and can't seem to find the right combination:

 public class A
 {
     public string Name { get; set; }

     [Column(TypeName = "jsonb")] 
     public List<B> Tags { get; set; }
 }

 public class B
 {
     public Guid Id { get; set; }
     public string Name { get; set; }
 }

Using these model classes, I'm trying to find every A that has a B equal to a certain value and/or a B that is in a list. For the first scenario, I've tried the following with no success:

 var query = "{\"Id\": \"7aecbd2c-ae2e-4362-9bd6-1d569eb94849\"}";

 var test1 = await context.A
                          .Where(a => EF.Functions.JsonExistAny(a.B, query))
                          .ToListAsync(context.CancellationToken);

 var test2 = await context.A
                          .Where(a => EF.Functions.JsonContains(a.B, query))
                          .ToListAsync(context.CancellationToken);

 var test3 = await context.A
                          .Where(a => EF.Functions.JsonContained(query, a.B))
                          .ToListAsync(context.CancellationToken);

 var test4 = await context.A
                          .Where(a => a.B.Any(b => b.Id == Guid.Parse("7aecbd2c-ae2e-4362-9bd6-1d569eb94849")))
                          .ToListAsync(context.CancellationToken);

Any direction would be appreciated

1 Answer 1

5

you should use square brackets [] for jsonb array query.

solution:

var query = "[{\"Id\": \"7aecbd2c-ae2e-4362-9bd6-1d569eb94849\"}]";

var test2 = await context.A
                          .Where(a => EF.Functions.JsonContains(a.B, query))
                          .ToListAsync(context.CancellationToken);

Example query for jsonb array:

SELECT u."Id", u."Addresses"
FROM "Users" AS u
WHERE u."Addresses" @> '[{"Code": 10}]'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.