c# - 在 where 子句中浏览实体

标签 c# entity-framework where-clause

我在使用 Entity Framework 编写 linq 表达式时遇到了一些问题。我有两个相关实体。 Pago(付款)和 Cuota(股份)。在 Cuota,我有 id_prestamo(贷款 ID)。

我需要的是获得一次 Prestamo(贷款)的所有 Pago(付款)。但是因为我有仅与 Cuota 相关的 Pago,所以我必须从 Cuota 获取 id_prestamo。问题是我无法像这样导航 throw Cuota:

Lista_pagos = db.Pago.Where(x => x.Cuota.Prestamo.id_prestamo == prestamo.id_prestamo).ToList();

我也试过这个表达式,但它也不起作用:

Lista_pagos = db.Pago.Where(x => x.Cuota.Where(y => y.Prestamo.id_prestamo == prestamo.id_prestamo)).ToList();

我说它不起作用是因为我无法编译该应用程序。这个地方肯定有错误 x.Cuota.Where(y => 但不知道如何正确使用 where 语句。我明白了:

enter image description here

“委托(delegate)不接受 1 个参数”

有人知道我怎样才能正确地写出这个表达式吗?

下面附上实体关系

enter image description here

谢谢!

最佳答案

您的查询中存在语法错误。

db.Pago.Where() 

...接受一个谓词——一个返回 bool 的函数.

x.Cuota.Where()

...返回 IQueryable<Cuota>

所以:

db.Pago.Where(x => x.Cuota.Where( ... ))

...是无效代码,因为 IQueryable<Cuota>不是 bool .

认为您真正想要的是:

Lista_pagos = db.Pago.Where(
    x => x.Cuota.Any(y => y.Prestamo.id_prestamo == prestamo.id_prestamo)
).ToList();

(注意 Any 而不是 Where 。)

关于c# - 在 where 子句中浏览实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14055144/

相关文章:

c# - 从大文本文件中读取 unicode 字符

.net - 将工作单元和存储库模式与 Entity Framework 结合使用的好处

c# - SQL Server 表中的并行插入/更新

sql - 在where子句中使用IIF语句

python - np.where 用字符串创建缺失值

c# - .NET 的 Array.Sort() 方法使用哪种排序算法?

c# - 如何将对象列表传递给 MVC4 中的 Controller 方法?

c# - 抛出异常 C# 进阶

c# - Entity Framework 核心 : How to dynamically get the DbSet from a derived Type?

PHP/MySQL : Update Query where value is missing from WHERE clause