使用Include语句中的Where子句进行Linq查询

Phi*_*ilo 7 c# linq asp.net entity-framework

我试图取代我的大丑陋查询; 虽然丑陋但它可以按预期工作: -

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;
}
Run Code Online (Sandbox Code Playgroud)

使用以下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();
Run Code Online (Sandbox Code Playgroud)

我在查询的第二行爆炸......一旦我添加了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();
Run Code Online (Sandbox Code Playgroud)

但后来我收到以下错误: -

运算符'&&'不能应用于'bool'和'System.Collections.Generic.IEnumerable类型的操作数

我知道这个概念是正确的,但我需要语法方面的帮助.

Jam*_*iec 12

你不能拥有一个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();
Run Code Online (Sandbox Code Playgroud)


小智 11

.Net 5 中添加了过滤包含功能(EF Core 5.0)。

支持的操作有:Where、OrderBy、OrderByDescending、ThenBy、ThenByDescending、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();
}
Run Code Online (Sandbox Code Playgroud)

MSDN 参考:https : //docs.microsoft.com/en-us/ef/core/querying/related-data/eager