【问题标题】:Retrieving a subset of rows from an OData endpoint从 OData 端点检索行的子集
【发布时间】:2017-02-15 01:29:29
【问题描述】:

我有一个公开 OData 端点的 ASP.NET Web API 2。

在前端,我使用的是 ASP.NET MVC 5。为了使用端点,我使用的是 WCF 服务引用

我面临的问题是我需要从给定 ID 列表的端点检索行的子集。

这是我在 OData 端点中使用的实体

class MyEntity
{
  public int ID {get; set;}
  public string Name {get; set;}
  public int Age {get; set;}
}

使用 LINQ 我已经在其他情况下使用以下语句解决了这个问题

var result = entitiesContext.MyEntity
  .Where(x => idsEmployees.Select(y => y).Contains(x.ID));

其中 idsEmployees 是我需要检索的员工 ID 列表。

在当前场景中使用此语句,我得到以下异常:

将 Linq 表达式转换为 URI 时出错:方法“包含”不是 支持。

我该如何解决这个问题?

谢谢。

【问题讨论】:

标签: c# asp.net-mvc linq asp.net-web-api odata


【解决方案1】:

经过一番挖掘,我在此博客中找到了解决方案

https://blogs.msdn.microsoft.com/phaniraj/2008/07/16/set-based-operations-in-ado-net-data-services/

这是解决问题的扩展方法

/// <summary>
/// Retrieves the subset of entities in a table exposed through OData
/// </summary>
/// <typeparam name="T">Entity type</typeparam>
/// <typeparam name="U">Subset type</typeparam>
/// <param name="query"></param>
/// <param name="Set"></param>
/// <param name="propertyExpression"></param>
/// <returns></returns>
public static DataServiceQuery<T> SubSet<T, U>(
    this DataServiceQuery<T> query, 
    IEnumerable<U> Set, 
    Expression<Func<T, U>> propertyExpression)
{
    //The Filter Predicate that contains the Filter criteria
    Expression filterPredicate = null;
    //The parameter expression containing the Entity Type
    var param = propertyExpression.Parameters.Single();
    //Get Key Property 
    //The Left Hand Side of the Filter Expression
    var left = propertyExpression.Body;
    //Build a Dynamic Linq Query for finding an entity whose ID is in the list
    foreach (var id in Set)
    {
        //Build a comparision expression which equats the Id of the Entity with this value in the IDs list
        // ex : e.Id == 1
        Expression comparison = Expression.Equal(left, Expression.Constant(id));
        //Add this to the complete Filter Expression
        // e.Id == 1 or e.Id == 3
        filterPredicate = (filterPredicate == null) 
            ? comparison 
            : Expression.Or(filterPredicate, comparison);
    }

    //Convert the Filter Expression into a Lambda expression of type Func<Lists,bool>
    // which means that this lambda expression takes an instance of type EntityType and returns a Bool
    var filterLambdaExpression = 
        Expression.Lambda<Func<T, bool>>(filterPredicate, param);
    return (DataServiceQuery<T>)query.Where<T>(filterLambdaExpression);
}

这是使用它的方法

var result = entitiesContext.MyEntity.Subset<MyEntity, int>(idsEmployees, x => x.ID);

【讨论】:

    猜你喜欢
    • 2018-03-21
    • 2016-06-10
    • 1970-01-01
    • 1970-01-01
    • 2018-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    相关资源
    最近更新 更多