1

我正在使用Microsoft.Data.Odata(5.6) 运行以下查询:

IEnumerable<Service> services = context.Services.Expand(ServiceQueryExpansion)
    .Where(c =>
        (serviceNames.Any(s => s.Equals(
            c.ServiceName, StringComparison.OrdinalIgnoreCase))))

serviceNames 是字符串的 IEnumerable

尝试上述查询时出现以下错误:

Error translating Linq expression to URI: The source parameter for the 'Any' method has to be either a navigation or a collection property.

我该如何解决这个问题?

4

3 回答 3

3

我知道这很有趣且令人兴奋(讽刺),但您可以像这样动态构建您的 Where 表达式:

var serviceNames = new string[] { "SERVICE1","SERVICE2"};

Expression<Func<Service,bool>> inList = v => false;
var parameter = inList.Parameters[0];
var propertyExpression = Expression.Property(parameter,"ServiceName");

foreach (var serviceName in serviceNames)
{
   var body = inList.Body;
   var constantExpression = Expression.Constant(serviceName);
   var equalityExpression = Expression.Equal(propertyExpression,constantExpression);

   body = Expression.OrElse(body,equalityExpression);

   inList = Expression.Lambda<Func<Service, bool>>(body, parameter);
}

IEnumerable<Service> services = context.Services.Expand(ServiceQueryExpansion)
    .Where(inList);

此方法从您的列表中构建一个自定义 where 子句,类似于 (v => v.ServiceName == "Service1" || v.ServiceName == "Service2" || v.ServiceName == "Service3")

您可能可以按照我的博客https://secureapplicationlifestyle.com/2013/07/filter-pattern-for-linq-query-filter.html中的指示将此逻辑封装到自定义“WhereContains(yourListHere)”自定义过滤器扩展中方法。

于 2013-08-29T14:29:31.717 回答
0

我所做的是尽可能应用过滤器,然后在本地获得结果后列出并制作另一个过滤器。

var services = context.Services.Expand(ServiceQueryExpansion).ToList();
services = services.Where(s => serviceNames.Any(n => n.ServiceName.Equals(s, StringComparison.OrdinalIgnoreCase)));

如果您有多个不需要通过网络获取的记录,这不是最佳选择。

另一种选择是创建数据服务操作。

[WebGet]
public IQueryable<Service> GetServicesByServiceName(string serviceNames)
{
    var serviceNamesArray = serviceNames.Split(',');
    var ctx = YourContext();
    return ctx.Services.Include("ServiceQueryExpansion").Where(s => serviceNamesArrays.Any(n => s.ServiceName.Equals(n, StringComparison.OrdinalIgnoreCase))).AsQueryable();
}
于 2014-09-29T03:01:59.120 回答
0

你可以写:

var services = context.Services.Expand(ServiceQueryExpansion).AsEnumerable()
      .Where(c => serviceNames.Contains(c.ServiceName));

但它会下载整个服务集合。或者:

var services = serviceNames.SelectMany(s=>
     context.Services.Expand(ServiceQueryExpansion).Where(c=> c.ServicaName == s));

这将创建 N 个请求。

我不知道在 Linq to OData 中有更好的方法来做到这一点。

于 2013-08-29T12:47:38.170 回答