Search code examples
asp.net-web-apiodata

does OData supports groupby for Enum type?


Version of OData:

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Microsoft.AspNet.OData" version="5.9.1" targetFramework="net45" />
  <package id="Microsoft.OData.Core" version="6.15.0" targetFramework="net45" />
  <package id="Microsoft.OData.Edm" version="6.15.0" targetFramework="net45" />
  <package id="Microsoft.Spatial" version="6.15.0" targetFramework="net45" />
</packages>

Enum for color:

public enum Color
{
    Red = 1,
    Green = 2,
    Blue = 3
}

Vehicle class:

public class Vehicle
{
    public Guid VehicleId { get; set; }
    [JsonConverter(typeof(StringEnumConverter))]
    public Color? Color { get; set; }
}

Web API endpoint:

[HttpGet]
[Route("vehicles")]
public IHttpActionResult GetVehicles(ODataQueryOptions<Vehicle> options)
{
    var query = dbContext.Vehicle.Select(x => new Vehicle
        {
            VehicleId = x.VehicleId,    // guid type for x.VehicleId
            Color = (Color?)x.ColorId    // nullable int type for x.ColorId
        });

    var odataQuery = options.ApplyTo(query) as IQueryable<object>;

    return Ok(odataQuery.AsEnumerable<Vehicle>());
}

Scenario 1:

Try http://localhost:1000/vehicles?$apply=groupby((vehicleId)) and it's working.

Scenario 2:

But with http://localhost:1000/vehicles?$apply=groupby((color)), this will throw error message ("exceptionMessage": "Argument types do not match").


Solution

  • Here's the answer from the odata.org google group.

    From a specification perspective enum types are primitive types, so they can be used in groupby.

    This does however not guarantee that your preferred tool set already supports this.