实体框架中包含的子查询

时间:2021-05-14 17:42:36

标签: c# entity-framework-core

我有一个带有实体框架 5 的 C# 应用程序。数据模型如下所示:

public class Challenge
{
    //Other properties
    public ICollection<UserChallenge> UserChallenges { get; set; }
}

public class UserChallenge
{
    public int Id { get; set; }

    public int ChallengeId { get; set;}

    public int ProfileId { get; set; }

    public int? GroupId { get; set; }

    //Other properties
}   

用户参与了挑战,我将此信息存储在 UserChallenges 表中。此外,用户被分成每组 10 名参与者。

我想编写一个查询,返回用户参与的所有挑战,结果包含来自用户组的 UserChallenges。

问题是我想在一个查询中完成并尽可能地优化它。

我现在有以下代码:

public Task<Challenge[]> GetChallenges(int profileId)
{
    context.Challenges
           .Where(c => c.UserChallenges.Any(uc => uc.ProfileId == profileId))
           .Include(c => c.UserChallenges);
           //I need to use GroupId somehow here
}

但是,它包含所有用户挑战。 是否可以过滤它们? 可能我可以使用 EF 5 中引入的 Included 过滤器。

1 个答案:

答案 0 :(得分:0)

添加 groupId 检查以根据 profileId 和 groupId 过滤挑战

public Task<Challenge[]> GetChallenges(int profileId, int groupId)
{
    context.Challenges
           .Where(c => c.UserChallenges.Any(uc => uc.ProfileId == profileId && uc.GroupId == groupId))
           .Include(c => c.UserChallenges);
}

如果您只想为该特定组包含 UserChallenges,您可以在 Include 方法中添加 Where 方法调用。

public Task<Challenge[]> GetChallenges(int profileId, int groupId)
{
    context.Challenges
           .Where(c => c.UserChallenges.Any(uc => uc.ProfileId == profileId && uc.GroupId == groupId))
           .Include(c => c.UserChallenges.Where(uc => uc.GroupId == groupId));
}
相关问题