如何过滤IList子查询EF Core 2.2

时间:2019-09-06 10:06:38

标签: c# asp.net-core-2.2 ef-core-2.2

我有以下(简化的)模型:

public class Participant {
    public Guid Id { get; set; }
    public string Name { get; set; }
    public Guid TeamId { get; set; }
    public Team Team { get; set; }
}

public class Team {
    ...
}

public class Activity {
    public Guid Id { get; set; }
    public string Name { get; set; }
    public int Status { get; set; }
    public IList<ActivityAttendee> ActivityAttendees { get; set; }
}

public class ActivityAttendee {
    public Guid Id { get; set; }
    public Guid ActivityId { get; set; }
    public Guid ParticipantId { get; set; }
    public int Status { get; set; }
    public Participant Participant { get; set; }
}

通过以下方式识别参与者:

Guid? participantId = Guid.TryParse(HttpContext.User.Claims.FirstOrDefault(c => c.Type == "Id")?.Value, out Guid tmp) ? (Guid?)tmp : null;

我查询这样的活动:

var activities = await _context.Activities.Include(x => x.ActivityAttendees).ThenInclude(x => x.Participant).Where(x => x.Status == 1).AsNoTracking().ToListAsync();

现在,我需要过滤参与者参加的活动。我尝试过:

var participantActivities = activities.Where(x => x.ActivityAttendees.ParticipantId == participantId);

var participantActivities = activities.Where(x => x.ActivityAttendees.Contains(y => x.ActivityAttendees.Where(z => z.ParticipantId == participantId)));

var participantActivities = activities.Where(x => x.ActivityAttendees.Any(y => y.ParticipantId == participantId))

我该怎么做?

在“普通” SQL中,我将执行以下操作:

SELECT Id, Name FROM Activities WHERE Id IN (Select ActivityId FROM ActivityAttendees WHERE ParticipantId = participantId))

接下来,我还需要过滤参与者没有参加但团队成员参加的活动(由ActivityAttendee.Participant.TeamId分组),但是我想我可以在回答上述问题时做到这一点。< / p>

1 个答案:

答案 0 :(得分:0)

正确的方法是:

var participantActivities = activities.Where(x => x.ActivityAttendees.Any(y => y.ParticipantId == participantId));