【问题标题】:Using another list in an Entity Framework query在实体框架查询中使用另一个列表
【发布时间】:2021-06-05 22:42:42
【问题描述】:

希望实现以下目标,但由于locations.Any() 被视为IEnumerable 而不是IQueryable 而失败,并且通过EF 调用的标量函数需要IQueryable。我需要这个过滤器发生在数据库级别(不是首先实现列表)。

我怎样才能在这里将locations.Any() 视为IQueryable?我知道该列表在数据库中不存在,但实体框架有没有办法理解这一点并在 SQL 中使用嵌套的 OR 构建和 AND 语句?



public Address GetAddresses(List<Loctions> locations)
{
   _context.Addresses.
      Where(a => locations.Any(l => MyContext.CustomFunction(l.PropA,l.PropB,  a.PropA, a.ProbB) > 1 ))
}
[DbFunction("fn_DistanceBetweenCoordinates", "dbo")]
public static decimal CustomFunction(decimal SourceLatitude, decimal SourceLongitude, decimal TargetLatitude, decimal TargetLongitude) {
            throw new NotImplementedException();
}

【问题讨论】:

  • _context.Addresses.AsEnumerable().Where(a =&gt; locations.Any(l =&gt; MyContext.CustomFunction(l.PropA, a.PropB) &gt; 1 ))怎么样
  • 这会将所有地址加载到内存中,因此它不是一个有效的查询。
  • 您使用的是经典的完整实体框架 - 还是实体框架核心?你有两个标签 - 不清楚它到底是什么....
  • 我不确定它是否会起作用,但您是否尝试将PropAPropB 选择到元组列表中,然后在查询中使用此列表而不是直接使用locations?我还没有测试过,但我可以想象这可以工作......
  • 你试过a =&gt; locations.AsQueryable().Any(...)吗?

标签: sql linq entity-framework-core linq-to-entities


【解决方案1】:

您可以通过将 CustomFunction 移入数据库并在从 EF 查询时使用该服务器端函数来实现这一点。

请阅读User defined function mapping 并尝试根据您的用例调整示例。

我们还没有看到 CustomFunction 的主体,因此无法判断从基于客户端的 UDF 到基于服务器的传输是否可行。

我们也不知道位置列表是如何填充的。根据具体的实现方式,示例代码的改编可能会变得更加繁琐。

【讨论】:

  • 在帖子中添加了自定义函数
猜你喜欢
  • 1970-01-01
  • 2012-07-17
  • 1970-01-01
  • 2017-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多