我在使用 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 语句。我明白了:
“委托(delegate)不接受 1 个参数”
有人知道我怎样才能正确地写出这个表达式吗?
下面附上实体关系
谢谢!
最佳答案
您的查询中存在语法错误。
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/