11

Basically,

I would like to convert odata query expression "$filter", "itemID eq 1" to where(w=>w.itemID==1)

Is there a ready library for this operation? Otherwise I need to code it by using DynamicLinq classes and linqKit.

3 Answers 3

11

I'm using Microsoft WebAPI with the following NuGet packages installed:

http://nuget.org/packages/Microsoft.Data.OData/

http://nuget.org/packages/microsoft.aspnet.webapi.odata

Which lets me write things like:

using System.Web.Http;
using System.Web.Http.OData.Query;

// Some stuff left out

[Queryable]
public IQueryable<Item> Get(ODataQueryOptions<Item> query)
{        
    var items = query.ApplyTo(from item in context.Items select item);
    return (IQueryable<Item>) items;
}

Then I can call it using jQuery Ajax (for the sake of the example, I prefer to use BackboneJS) like this:

$.ajax({ url: '/api/items', data: $.param({ '$filter': 'ID eq 1' }) });

Which will then return only the items with an ID equal to 1, which I think is what you are after?

If itemID is the main ID of the object you are retrieving, I would probably follow REST principles and create and API where the url to retrieve an item with the ID of 1 would be:

/api/items/1

And only use oData queries on the collection of items if I was querying based on other properties of the items in the collection, or do something like below for example when retrieving the top 10 records.

$.ajax({ url: '/api/items', data: $.param({ '$top': 10 }) });
1
  • query.ApplyTo seems what I'm looking.I need it on mono. Thank you. Mar 21, 2013 at 6:48
5

You can use following NuGet package to apply filter: https://www.nuget.org/packages/Community.OData.Linq

Code sample would be:

using System.Linq;
using Community.OData.Linq;

// dataSet in this example - any IQuerable<T> 
Sample[] filterResult = dataSet.OData().Filter("Id eq 2 or Name eq 'name3'").ToArray();

Currently supported: filter and orderby in v4 format

0

You Can use Microsoft.Rest.Azure.OData

string filter = new ODataQuery(x => x.itemID == 1).Filter;

1
  • Thanks for your contribution. 1 year later it'll be a decade after the question. I'm happy to see some improvement in .net libs, even I moved to java back meantime :) May 12, 2022 at 16:23

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.