【问题标题】:Need a lambda expression to have an include with a where clause [duplicate]需要一个 lambda 表达式才能包含一个 where 子句 [重复]
【发布时间】:2020-01-09 00:29:49
【问题描述】:

我需要获取包含歌曲列表的 Decades 列表。

关键是我需要一个 ACTIVE Decades 列表以及 ACTIVE 歌曲。

这是我的模型:

Decades

Songs

这是我目前所拥有的:

Decades = await _context.Decades
                .Include(x => x.Songs)
                .Where(x => x.Active == true && x.Songs.Any(s => s.Active == true))
                .OrderBy(x => x.DecadeId)
                .ToListAsync()

但我得到的是处于活动状态的 Decades,但歌曲无关紧要 - 无论 ACTIVE 标志如何,我都会得到它们。

想法?

这是我想出的解决方案 - 在 Jawad 的帮助下 - 对于那些可能觉得有用的人:

           Decades = await _context.Decades
                .Include(x => x.Songs)
                .Where(x => x.Active == true)
                .OrderBy(x => x.DecadeId)
                .Select(x => new Decade()
                {
                    DecadeId = x.DecadeId,
                    DecadeText = x.DecadeText,
                    DecadeExtended = x.DecadeExtended,
                    Description = x.Description,
                    Active = x.Active,
                    Added = x.Added,
                    Songs = x.Songs
                        .Where(s => s.Active == true).ToList()
                }).ToListAsync()

【问题讨论】:

  • 在 EF 中没有任何规定可以在单个查询中过滤包含的内容。见this answer

标签: c# .net linq


【解决方案1】:

您将无法过滤掉通过 include 语句引入的列表。您将需要使用Select 语句来获取按您想要的方式过滤子列表的数据。像这样的,

    Decades = await _context.Decades
                .Include(x => x.Songs)
                .Where(x => x.Active)
                .OrderBy(x => x.DecadeId)
                .Select(x => new Decade() { 
                   x.DecadeId,
                   ...
                   x.Added,
                   Songs = x.Songs.Where(x => x.Active)
                 })
                .ToListAsync();

【讨论】:

【解决方案2】:

您可以获得所有活跃的十年,然后获得所有活跃的歌曲并根据需要组合可枚举。

不会花费更多时间,因为如果在数据库端触发 Join 操作是一项相当昂贵的操作。

var decades = await _context.Decades
            .Where(x => x.Active)
            .ToListAsync();
var songs = await _context.Songs
            .Where(x => x.Active)
            .ToListAsync();
return decades.Select(x => new { Decade = x, Songs = songs.Where(s => s.DecadeId == x.Id)});

它可能可以用 GroupBy 或其他东西更有效地重写,但它应该可以工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-09
    • 2014-07-18
    • 2010-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-31
    • 1970-01-01
    相关资源
    最近更新 更多