OData “where ID in list” query

前端 未结 4 1631
天命终不由人
天命终不由人 2020-12-13 06:05

I have an OData service where I\'m trying to filter by a list of IDs; the SQL equivalent would be something like:

SELECT * FROM MyTable WHERE TableId IN (100         


        
4条回答
  •  时光取名叫无心
    2020-12-13 06:32

    See accepted answer, everything below is for OData v < 4.01

    try this one

     var ids = new [] { 100, 200, 300 } ;
     var res = from m in provider.Media 
               from id in ids 
               where m.media_id == id 
               select m;
    

    there is a comprehensive description on msdn on querying DataServices.

    another approach would be

    var results = provider.Media
       .AddQueryOption("$filter", "media_id eq 100");
    

    and since OData doesn't support IN statements you will come up with filter condition like this

    .AddQueryOption("$filter", "(media_id eq 100) or (media_id eq 200 ) or ...");
    

    which you can build using loop or linq Select and string.Join:

    var ids = new [] { 100, 200, 300 };
    var filter = string.Join(" or ", ids.Select(i=> $"(media_id eq {i})"));
    var results = provider.Media.AddQueryOption("$filter", filter);
    

    UPDATE: There is filter operation field=["a","b"] however it means something different.

    UPDATE2: In OData V4 there is lambda expressions any and all, paired with array literal ["a", "b"] they might work as in but I was not able to come up with working example using v4 endpoint at OData.org

提交回复
热议问题