2017-02-14 47 views
1

我有一个暴露OData端点的ASP.NET Web API 2。从OData端点检索行的子集

在前端我使用的是ASP.NET MVC 5.为了使用端点,我使用了一个WCF Services References

我面临的问题是我需要从给出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:该方法“包含”不 支持。

我该如何解决这个问题?

谢谢。

+0

'$ filter' may be你在找什么,但我不积极(问题是一个令人困惑的)https://docs.microsoft.com/en-us/aspnet/web-api/overview/odata-support-in-aspnet-web- api/supporting-odata-query-options –

+0

是OData v4,对不对?从客户端过滤? – octavioccl

+0

@octavioccl是 – vcRobe

回答

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