应用Distinct到OData查询

Snæ*_*ørn 6 c# odata asp.net-web-api-odata odata-v4

我想从OData端点获取不同值的列表.但不支持distinct或group by.

我的URI查询看起来像这样

GET /odata/Products?$select=foo & $top=10 & $count=true & distinct=true
Run Code Online (Sandbox Code Playgroud)

我的控制器

[EnableQuery]
public IQueryable<FooBarBaz> Get(ODataQueryOptions<FooBarBaz> queryOptions, bool distinct)
{
        //I've tried the following
        return Repository.AsQueryable().Distinct();

        // and
        return Repository.AsQueryable().GroupBy(x => x.Foo);

        // and
        IQueryable query = queryOptions.ApplyTo(Repository.AsQueryable());
        return query.Distinct(); // Can't call .Distinct() here
}
Run Code Online (Sandbox Code Playgroud)

没有工作:(

Chr*_*ler 9

因为您已经指定了EnableQuery属性,所以您可以使用$ apply to groupby您的不同字段,而无需添加任何自定义函数或参数,您可以免费获得这个:

GET /odata/Products?$apply=groupby((foo))&top=10&$count=true
Run Code Online (Sandbox Code Playgroud)

这是简单的OData v4标准语法,不需要任何代码修改即可实现.不要更改要支持不同查询的每个控制器,您不能提前100%知道您的客户端应用程序可能需要此功能的控制器,因此请使用在开始自定义之前提供的功能.

当然,这种方法有一个警告,它不会在100%的时间内使其可行:

  • $ filter和$ orderby只能对group by子句中指定的字段进行操作

这可能要求您在分组语句中包含其他字段,对于某些复杂的过滤,结果数据集可能不会令人满意,在这种情况下我们发现更容易支持通过HTTP标头传递额外的预过滤参数在应用传入的查询选项之前应用于查询,请注意这只是必要的,因为我们的过滤条件是租约和安全性相关的,因此如果忽略安全描述符,结果数据集会有更多重复的条目.

只是为了好玩,这是我们的自定义GET函数,如果传入它,则应用预过滤器:

[EnableQuery]
public IQueryable<FooBarBaz> Get(ODataQueryOptions<FooBarBaz> queryOptions, bool distinct)
{
    DbQuery<FooBarBaz> query = Repository;
    query = this.ApplyUserPolicy(query);
    return Ok(query);
}
Run Code Online (Sandbox Code Playgroud)

以下是在基类中实现的,因此我们在每个控制器中都没有它:

/// <summary>
/// Apply default user policy to the DBQuery that will be used by actions on this controller.
/// The big one we support here is X-Filter HTTP headers, so now you can provide top level filtering in the header of the request 
/// before the normal OData filter and query parameters are applied.
/// This is useful when you want to use $apply and $filter together but on separate sets of conditions.
/// </summary>
/// <param name="dataTable">DBQuery to apply the policy to</param>
/// <returns>Returns IQueryable entity query ready for processing with the headers applied (if any)</returns>
private IQueryable<TEntity> ApplyUserPolicy(DbQuery<TEntity> dataTable)
{
    // Proprietary Implementation of Security Tokens
    //var tokenData = SystemController.CurrentToken(Request);
    //IQueryable<TEntity> query = ApplyUserPolicy(dataTable, tokenData);
    IQueryable<TEntity> query = dataTable.AsQueryable();

    // Now try and apply an OData filter passed in as a header.
    // This means we are applying a global filter BEFORE the normal OData query params
    // ... we can filter before $apply and group by

    System.Collections.Generic.IEnumerable<string> filters = null;
    if (Request.Headers.TryGetValues("X-Filter", out filters))
    {
        foreach (var filter in filters)
        {
            //var expressions = filter.Split(',');
            //foreach (var expression in expressions)
            {
                var expression = filter;
                Dictionary<string, string> options = new Dictionary<string, string>()
                {
                    { "$filter"  , expression },
                };

                var model = this.Request.ODataProperties().Model;
                IEdmNavigationSource source = model.FindDeclaredEntitySet(this.GetEntitySetName());
                var type = source.EntityType();
                Microsoft.OData.Core.UriParser.ODataQueryOptionParser parser
                    = new Microsoft.OData.Core.UriParser.ODataQueryOptionParser(model, type, source, options);
                var filterClause = parser.ParseFilter();     // parse $filter 

                FilterQueryOption option = new FilterQueryOption(expression, new ODataQueryContext(model, typeof(TEntity), this.Request.ODataProperties().Path), parser);
                query = (IQueryable<TEntity>)option.ApplyTo(query, new ODataQuerySettings());
            }
        }
    }


    return query;
}
Run Code Online (Sandbox Code Playgroud)

如果没有别的,尝试向您的经理出售AdaptiveLINQ会更便宜:)

  • 在这种情况下,我将创建一个自定义的“IQueryable”_Function_端点来服务不同的记录集,或者不分页数据。330 个值并不是很多,如果您确实想要分页视图,您可以通过一次点击将其恢复并管理客户端上的分页。对“Distinct”的需求通常表明您没有足够规范化的数据结构,或者您正在从错误的控制器执行查询,从已经提供不同记录的控制器提供查询。 (2认同)

Rav*_*try 8

通过在资源上定义集合Action来解决问题的最佳解决方案.

第一步:在WebApiConfig.cs中配置"Distinct"操作

ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<FooBarBaz>("FooBarBazs");//Resource Name

ActionConfiguration Distinct = builder.Entity<FooBarBaz>().Collection.Action("Distinct");//Name of the action method
Distinct.ReturnsCollectionFromEntitySet<FooBarBaz>("FooBarBazs");//Return type of action
Distinct.Parameter<string>("On");//Property on which collection is filtered as Distinct

config.Routes.MapODataRoute("odata", "odata", builder.GetEdmModel());
Run Code Online (Sandbox Code Playgroud)

第二步:在FooBarBazsController.cs中添加Action,它返回不同实体的集合

[EnableQuery]//enable the $select,$expend Queries
[HttpPost]//All the action methods are of post type in Web api
public IQueryable<FooBarBaz> Distinct(ODataActionParameters parameters)
{
        string on = "";
        if (!ModelState.IsValid)
        {
            throw new HttpResponseException(HttpStatusCode.BadRequest);
        }

        try
        {
             on = parameters["On"] as string;
        }
        catch (NullReferenceException ex)
        {
            HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.BadRequest);
            message.Content = new StringContent("{\"Error\":\"Invalid Query -> On property is not defined\"}");
            throw new HttpResponseException(message);
        }
        catch (Exception ex)
        {
            throw new HttpResponseException(HttpStatusCode.BadRequest);
        }


        PropertyInfo[] props = new FooBarBaz().GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
        var isPropertyExist = false;
        for (int i = 0; i < props.Length; i++)
        {
            if (props[i].Name.Equals(on))
            {
                isPropertyExist = true;
                break;
            }
        }


        if (isPropertyExist)
        {
            var fooBarBazCollection = db.fooBarBazs.GroupBy(GetGroupKey(on)).Select(g => g.FirstOrDefault());//Select the Distinct Entity on the basis of a property
            return fooBarBazCollection ;
        }
        else
        {
            HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.BadRequest);
            message.Content = new StringContent("{\"Error\":\"Property '"+on+"' Not Exist}");
            throw new HttpResponseException(message);
        }
}
Run Code Online (Sandbox Code Playgroud)

第三步:添加一个静态方法,该方法根据Property Name返回groupby的Expression.

private static Expression<Func<fooBarBaz, string>> GetGroupKey(string property)
    {
        var parameter = Expression.Parameter(typeof(fooBarBaz));
        var body = Expression.Property(parameter, property);
        return Expression.Lambda<Func<fooBarBaz, string>>(body, parameter);
    } 
Run Code Online (Sandbox Code Playgroud)

现在构建项目,您可以像这样查询资源

POST /odata/FooBarBazs/Distinct HTTP/1.1
Host: localhost:9360
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 6d174086-7b97-76a2-679c-4dab3dfb5938

{"On":"PropertyName"} 
Run Code Online (Sandbox Code Playgroud)

并且还可以像这样使用$ select和$ extend

POST /odata/FooBarBazs/Distinct?$select=PropertyName1,PropertyName2 HTTP/1.1
Host: localhost:9360
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 6d174086-7b97-76a2-679c-4dab3dfb5938

{"On":"PropertyName"} 
Run Code Online (Sandbox Code Playgroud)

我希望这能解决问题.+1,如果它.