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

时间:2015-11-04 17:26:34

标签: c# asp.net entity-framework linq

我正在尝试替换我那个大而丑陋的查询;虽然丑陋但它的工作原理如下: -

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'类型的操作数和' System.Collections.Generic.IEnumerable

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

2 个答案:

答案 0 :(得分:10)

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();

答案 1 :(得分:3)

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

支持的操作有:Where,OrderBy,OrderByDescending,ThenBy,ThenByDescending,跳过和获取

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://docs.microsoft.com/en-us/ef/core/querying/related-data/eager