c# – 如何在asp.net mvc web api中为OData服务返回动态启用排序

这是我的控制器的代码:

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());
        }
    }

当我尝试进行此调用/ api / RegularGrig?entityName = SecurityPrincipal& $orderby = Id

我收到这个例外

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

那么,有没有办法对动态数据进行排序/过滤?

最佳答案 这段代码现在适用于我:

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());
}
点赞