简体   繁体   English

如何在ASP.NET MVC Web API中为返回动态的OData服务启用排序

[英]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 当我尝试拨打此电话时/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? 那么,有什么方法可以对动态数据进行排序/过滤?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM