xumix
xumix

Reputation: 643

How can I enable sorting for OData service returning dynamic in asp.net mvc web api

Here is the code for my controller:

public class RegularGrigController : ApiController
    {
        // GET api/regulargrig
        public IEnumerable<string> Get()
        {
            return EntityHelper.GetEntities().Select(t => t.ModelName());
        }

        public PageResult<dynamic> Get(string entityName, ODataQueryOptions options)
        {
            var query = EntityHelper.GetQueryable(entityName).Select("new (Id, SysName)"); // Dynamic queryable

            IQueryable results = options.ApplyTo(query); // Exception here

            return new PageResult<dynamic>(results as IEnumerable<dynamic>, Request.GetNextPageLink(), Request.GetInlineCount());
        }
    }

When I try to make this call /api/RegularGrig?entityName=SecurityPrincipal&$orderby=Id

I receive this exception

Type 'System.Object' does not have a property 'Id'

So, is there any way to sort/filter dynamic data?

Upvotes: 4

Views: 1468

Answers (1)

xumix
xumix

Reputation: 643

This code works for me now:

public PageResult<dynamic> Get(string entityName)
{
    var query = EntityHelper.GetQueryable(entityName).Select("new (Id, SysName)");
    var modelBuilder = new ODataConventionModelBuilder();
    modelBuilder.AddEntity(query.ElementType);
    var model = modelBuilder.GetEdmModel();
    var options = new ODataQueryOptions(new ODataQueryContext(model, query.ElementType), this.Request);
    IQueryable results = options.ApplyTo(query);

    return new PageResult<dynamic>(results as IEnumerable<dynamic>, Request.GetNextPageLink(), Request.GetInlineCount());
}

Upvotes: 2

Related Questions