0

Lets say I have a query like this :

DataServiceQuery<Order> selectedOrders = context.Orders
    .AddQueryOption("$filter", "Freight gt 30")
    .AddQueryOption("$orderby", "OrderID desc");

I would like to append something like this using an IQueryable<Order>

.Where(o => o.OrderID > 10)

Is there a way this can be accomplished easily?

In my actual real-world scenario, both the existing Select/Expands and the .Where that is getting appended can be rather complex and I do not wish to attempt rewriting them with .AddQueryOption or Expressions. There are also a lot of them (it's for all the reports in our system), and the actual filter being added using AddQueryOption will be using a dynamic property name although the logic behind it should be the same.

I found I can cast the IQueryable to a DataServiceQuery as well and extract the $filter portion, but don't know how to alter/append it.

IQueryable<Order> orders = context.Orders
    .Where(o => o.OrderID > 10);

var dataServiceQuery = (DataServiceQuery<Order>)orders;
var filter = System.Web.HttpUtility.ParseQueryString(dataServiceQuery.RequestUri.Query)["$filter"];

// How do I change the filter to append " and Freight gt 30"?

I feel this should be something easy, but I'm still fairly to working with DataServiceQuery and my google skills are failing me.

Rachel
  • 130,264
  • 66
  • 304
  • 490
  • You can give it a try, it explains how to use AddQueryOption to write a LINQ query equivalent to a query. https://learn.microsoft.com/en-us/dotnet/api/system.data.services.client.dataservicequery-1.addqueryoption?view=netframework-4.8 – Lan Huang Nov 12 '21 at 07:33
  • I do not want to rewrite all my `.Where` linq queries to be `AddQueryOption` compatible because there are a lot of them and they can get rather complex. I suspect some may even be too complex to use with the `AddQueryOption` syntax as there are some limits with that – Rachel Nov 12 '21 at 14:38
  • 1
    Maybe you can refer to this article to write: https://stackoverflow.com/questions/15777219/how-to-dynamic-add-filters-to-a-linq-query-against-an-odata-source-in-c-sharp – Lan Huang Nov 15 '21 at 08:52
  • That is very similar to the solution I ended up with. I took my original query, extracted the $filter from it, and created a new DataServiceQuery that combines it with the new $filter using `.AddQueryOption("$filter", $"({originalFilter}) and ({appendedFilter})");` – Rachel Nov 15 '21 at 14:37

0 Answers0