Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linq

odata

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.

like image 404
Davut Gürbüz Avatar asked Mar 01 '13 09:03

Davut Gürbüz


2 Answers

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 }) });
like image 54
tom-19 Avatar answered Nov 19 '22 07:11

tom-19


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

like image 40
Ihar Yakimush Avatar answered Nov 19 '22 07:11

Ihar Yakimush