Search code examples
c#asp.net-core.net-coreodata

OData .Net Core Run Query But Returns Error


I'm using the OData Beta for .Net core and I'm trying to manually apply my odata filters so I can use them with my Rest Service Base logic. I can see that when I make a request my controller is hit but and returns the correct data but for some reason I'm receiving an error instead of my Data.

route: /api/ODataTest?$filter=not endswith(Name, 'ter')

error:

The query specified in the URI is not valid. The property 'Name' cannot be used in the $filter query option.

This is my Controller

[Route("api/ODataTest")]
public class ODataTestController : Controller
{
    CustomContext _context;
    IAdaptable<Skill, SkillDTO> _adapter;
    public ODataTestController(CustomContext context, IAdaptable<Skill, SkillDTO> adapter)
    {
        this._context = context;
        this._adapter = adapter;
    }

    [HttpGet]
    [EnableQuery]
    public async Task<SkillDTO[]> GetFilteredODataList(ODataQueryOptions<Skill> q)
    {
        var skillsQuery = this._context.Skills.AsQueryable();

        if (q?.Filter != null)
        {
            skillsQuery = q.Filter.ApplyTo(skillsQuery, new ODataQuerySettings()) as IQueryable<Skill>;
        }

        var skills = await skillsQuery.Select(s => this._adapter.ToDTO(s)).ToArrayAsync();
        return skills;
    }
}

and my Startup looks like so:

public void ConfigureServices(IServiceCollection services)
{
    services.AddOData();
    //....
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    //...
    app.UseMvc(routeBuilder =>
    {
         routeBuilder.MapODataServiceRoute("odata", null, GetModel());
         routeBuilder.EnableDependencyInjection();
    });
}

public static IEdmModel GetModel()
{
    var builder = new ODataConventionModelBuilder();
    var skillSet = builder.EntitySet<Skill>(nameof(Skill));
    builder.Namespace = "Astoot.Entities.Models";
    builder.ContainerName = "DefaultContainer";
    return builder.GetEdmModel();
}

The Filter definitely retrieves my data fine so why am I being returned this error?


Solution

  • Turns out I needed to globally Enable Filtering on my RouteBuilder

    app.UseMvc(routeBuilder =>
    {
        routeBuilder.Count().Filter().OrderBy().Expand().Select().MaxTop(null);
        routeBuilder.MapODataServiceRoute("odata", null, GetModel());
        routeBuilder.EnableDependencyInjection();
    });