【问题标题】:Linq to Entities with custom method in WhereLinq to Entity with custom method in Where
【发布时间】:2020-02-21 23:17:08
【问题描述】:

我有一个复杂的 LINQ to Entities 查询,表明 where 太长了。我想将它拆分为一些命名良好的方法,以便其他人可以理解它。这篇文章似乎暗示只要我返回一个表达式 EF 可以翻译,我就可以做到这一点。 https://stackoverflow.com/a/18338476/4812782

这是我的简化代码。我无法在过滤之前检索数据,因为它将超过 100,000 条记录。我的数据库是 Oracle。

var q = _context.vehicles
    .Where(x => IsActiveVehicle())
    .ToList()

Expression<Func<tb_vehicle, bool>> IsActiveVehicle()
            {
                return vehicle => vehicle.type == "R" &&
                       vehicle.status != "E" &&
                       vehicle.deleted == false;
            }

我得到了错误

无法将类型“System.Linq.Expressions.Expression>”隐式转换为“bool”。无法将 lambda 表达式转换为预期的委托类型,因为块中的某些返回类型不能隐式转换为委托返回类型

感谢任何帮助。

【问题讨论】:

  • 好像你想要Where(IsActiveVehicle())

标签: c# entity-framework linq linq-to-entities


【解决方案1】:

这是不正确的,如错误所示:

.Where(x => IsActiveVehicle())

这是创建一个包含您的表达式的新表达式。

您实际上希望将Expression&lt;Func&lt;&gt;&gt; 传递给.Where。

var q = _context.vehicles
    .Where(IsActiveVehicle())
    .ToList()

注意你链接的问题/答案,你会看到它。


另一种看待它的方式:

.Where(x => IsActiveVehicle())

意思是下面的废话:

.Where(x => ((vehicle) => vehicle.type == "R" &&
                       vehicle.status != "E" &&
                       vehicle.deleted == false))

但是,这个:

.Where(IsActiveVehicle())

意思如下,更有意义:

.Where(vehicle => vehicle.type == "R" &&
                       vehicle.status != "E" &&
                       vehicle.deleted == false)

【讨论】:

  • 我完全错过了!谢谢!!我可能会有大约 10 种这样的自定义方法。有没有办法将它们链接到一个 where 子句中,或者我需要为每个 where 子句添加一个新的 where 子句?
  • 如.Where(IsActiveVehicle && IsNotDocked())
  • 假设您打算用AND 链接它们,最好的方法是多次调用.Where()。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-29
  • 1970-01-01
  • 1970-01-01
  • 2014-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多