在Include语句中使用Where子句的Linq查询 [英] Linq Query with a Where clause in an Include statement
问题描述
我正在尝试替换我的笨拙的大查询;虽然很丑陋,但是可以按需工作:-
I am trying to replace my big, ugly query; although ugly it works as desired:-
using (var ctx = new Data.Model.xxxTrackingEntities())
{
var result = ctx.Offenders
.Join(ctx.Fees, o => o.OffenderId, f => f.OffenderId,
(o, f) => new { Offenders = o, Fees = f })
.Join(ctx.ViolationOffenders, o => o.Fees.ViolationId, vo => vo.ViolationId,
(o, vo) => new { Offenders = o, ViolationOffenders = vo })
.Join(ctx.Violations, v => v.ViolationOffenders.ViolationId, vo => vo.ViolationId,
(v, vo) => new { Violations = v, ViolationOffenders = vo })
.Where(o => o.Violations.Offenders.Offenders.YouthNumber != "")
.ToList();
gvwData.DataSource = result;
}
使用以下linq查询:-
with the following linq Query:-
var result = ctx.Offenders
.Include(o => o.Fees.Where(f => f.Amount != null))
.Include(o => o.ViolationOffenders)
.Include(o => o.ViolationOffenders.Select(of => of.Violation))
.Where(o => o.YouthNumber != "" && o.FirstName != "")
.ToList();
我正在查询的第二行...添加了where子句之后... o => o.Fees.Where(f=> f.Amount != null)
I am blowing up on the 2nd line of the query... once I add the Where clause... o => o.Fees.Where(f=> f.Amount != null)
我收到的错误消息...
The error message I get...
包含路径表达式必须引用在类型上定义的导航属性.使用虚线路径作为参考导航属性,使用选择"运算符作为集合导航属性.
The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties.
此外,我尝试将查询编写为:-
In addition, I tried writing my query as:-
var result = ctx.Offenders
.Include(o => o.Fees)
.Include(o => o.ViolationOffenders)
.Include(o => o.ViolationOffenders.Select(of => of.Violation))
.Where(o => o.YouthNumber != "" && o.FirstName != "" && o.Fees.Where(f=> f.Amount != null))
.ToList();
但随后出现以下错误:-
But then I get the following error:-
&&"运算符不能应用于类型为'bool'和'System.Collections.Generic.IEnumerable
Operator '&&' cannot be applied to operands of type 'bool' and 'System.Collections.Generic.IEnumerable
我知道这个概念是正确的,但是我需要语法方面的帮助.
I know the concept is right, but I need help with the syntax.
推荐答案
在Where
内不能有Where
,但是可以使用Any
来返回布尔值
You cant have a Where
inside the Where
, but you can use Any
which will return a boolean
var result = ctx.Offenders
.Include(o => o.Fees)
.Include(o => o.ViolationOffenders)
.Include(o => o.ViolationOffenders.Select(of => of.Violation))
.Where(o => o.YouthNumber != "" && o.FirstName != ""
&& o.Fees.Any(f=> f.Amount != null)) // here
.ToList();
这篇关于在Include语句中使用Where子句的Linq查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!