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

标签 c# dynamic asp.net-mvc-4 asp.net-web-api odata

这是我的 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());
        }
    }

当我尝试调用 /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());
}

关于c# - 如何在 asp.net mvc web api 中为返回动态的 OData 服务启用排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15764215/

相关文章:

c# - 登录 C# 库

由于猴子补丁的能力,.NET 4 可以实现更好的单元测试/模拟?

c++ - 如何返回没有指针的动态结构?

asp.net - 命名管道引用不适用于 ASP.NET MVC 4

c# - 如何写入隐藏文件?

c# - 按 Enter 键时出错,C# 控制台

c# - 确定某人是否打开了网页

asp.net-mvc-4 - ASP.NET MVC 路由配置将 Http 302 对象移至

c# - 使用 HttpContext.Current.Application 存储简单数据

jQuery - 动态添加元素的 on() 问题