在Include语句中使用Where子句的Linq查询
本文关键字:子句 Linq 查询 Where Include 语句 | 更新日期: 2023-09-27 18:20:30
我正在尝试替换我的又大又丑的查询;虽然丑陋,但它工作如所愿:-
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查询:-
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)
我收到的错误消息。。。
Include路径表达式必须引用在类型上定义的导航属性。对引用导航属性使用虚线路径,对集合导航属性使用Select操作符。
此外,我尝试将我的查询写成:-
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();
但后来我得到了以下错误:-
操作员的&;'不能应用于类型为"bool"answers"System.Collections.Generic.IEnumerable "的操作数
我知道这个概念是正确的,但我需要语法方面的帮助。
Where
中不能有Where
,但可以使用Any
,它将返回布尔
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();
在.Net 5中添加了过滤包含功能(EF Core 5.0)。
支持的操作有:Where、OrderBy、OrderByDescending、ThenBy、ThenByDescening、Skip和Take
using (var context = new BloggingContext())
{
var filteredBlogs = context.Blogs
.Include(blog => blog.Posts
.Where(post => post.BlogId == 1)
.OrderByDescending(post => post.Title)
.Take(5))
.ToList();
}
MSDN参考:https://learn.microsoft.com/en-us/ef/core/querying/related-data/eager