Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OData V4 + WebAPI Filter by Int Value of Enum?

OData V4 has enum support but it appears you have to search by the namespace only. How does one now search by the value instead of the text representation?

In V3 of odata you could query for $filter=Status eq 35, where 35 is Complete in the enum. This method would work, even if that field was an enum field in the data model.

Now this method fails in V4, instead requiring the namespace with text representation of the enum.

I want to get the V3 support working again without having to lose the other features of odata V4. Searching by the int value for the enum item seems more reliable than searching for text. Older odata clients (such as kendo) don't support a by-text enum filtering method.

like image 630
James Hancock Avatar asked Aug 25 '14 16:08

James Hancock


2 Answers

to do that in OData v4, we can enable the EnumPrefixFree in the initial webapi configuration, so we dont have to write the full enum namespace as prefix :

public static void Register(HttpConfiguration config)
{
    // ...
    config.EnableEnumPrefixFree(enumPrefixFree: true);
    config.MapODataServiceRoute("odata", "odata", YourEdmModem);
    // ...
}

then, we can filter any enum by String or Int value :

$filter=Status eq 'single'

or

$filter=Status eq 1

hope this helps.

like image 186
Chtiwi Malek Avatar answered Oct 23 '22 11:10

Chtiwi Malek


With v4, you have to add the namespace as the prefix and surround the value with the single quote such as http://services.odata.org/V4/(S(m1bhpaebr1yvzx5vtz5v4ur1))/TripPinServiceRW/People?$filter=Gender%20eq%20Microsoft.OData.SampleService.Models.TripPin.PersonGender'1' , where 1 represents Female.

Here is a quotation from the ABNF of the protocol http://docs.oasis-open.org/odata/odata/v4.0/os/abnf/odata-abnf-construction-rules.txt:

enum            = qualifiedEnumTypeName SQUOTE enumValue SQUOTE
enumValue       = singleEnumValue *( COMMA singleEnumValue )
singleEnumValue = enumerationMember / enumMemberValue
enumMemberValue = int64Value
like image 9
Tan Jinfu Avatar answered Oct 23 '22 11:10

Tan Jinfu