-2

I have a db table column where some properties are stored as json. Here is an example :

properties 
----------
{ "SortBy" : "ASC" }
List<MyItem> items = await this.dbContext.AllItems
    .Where(x => x.field.CompanyId== CompanyId)
    .OrderBy(x => x.Value);

I need to change the OrderBy based on that JSON value. It can be ASC, DESC, or no OrderBy() if there is no value in there.

The sort column "properties" is in the same table as AllItems. I will need to dynamically sort the column based on properties JSON.

Any suggestions?

4
  • 1
    1) "I need to change the OrderBy based on that JSON value" - is this a value stored in another table rather than AllItems? 2) What database are you using? 3) How would the query look in pure SQL? Commented Aug 9 at 5:49
  • Do you just need to change the sort direction (.OrderBy(...) vs .OrderByDecending(...)) or do you also need to dynamically select the sorted column (.OrderBy(x => x.SomeSortByColumn))? Commented Aug 10 at 0:07
  • in the same table as AllItems you can't use it in the same query. That's a very weird design. A SQL query can't automagically change its behavior based on data that didn't even exist when the SQL itself was compiled into an execution plan. You'll have to run one query to extract the JSON data, another to get the real data. Given how wasteful this is, if you don't have too many rows, you might as well load the data then sort in memory Commented Aug 11 at 13:50
  • What does the table actually look like? How would you get the result you want using SQL? Or was this design chosen without thinking about querying? If AllItems contains a company's orders, is the properties JSON repeated across all orders? Even though it doesn't change? Commented Aug 11 at 13:52

1 Answer 1

1

First of all you need to deserialize the JSON:

public record OrderDescriptor(string SortBy);

Then use it

var json = @"{ \"SortBy\" : \"ASC\" }";
var descriptor = JsonSerializer.Deserialize<OrderDescriptor>(json);

Then you can use it in your original context:

var queryable = this.dbContext.AllItems
    .Where(x => x.field.CompanyId== CompanyId);

if(descriptor.SortBy == "ASC") 
    return await queryable
        .OrderBy(x => x.Value)
        .ToListAsync();
else if(descriptor.SortBy == "DESC") 
    return await queryable
        .OrderByDescending(x => x.Value)
        .ToListAsync();

// Fallback to no ordering      
return await queryable.ToListAsync();
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.