Search code examples
linqodata

Is there a ODATA query to linq where expression (ODATA to Linq )


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.


Solution

  • 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 }) });