我在物體用戶和組之間有多對多的關系,我也有加入表 GroupParticipants。
public class User
{
public string Id {get; set;}
public ICollection<GroupParticipant> Group { get; set;}
}
public class Group
{
public int Id { get; set; }
public ICollection<GroupParticipant> Participants { get; set; }
}
public class GroupParticipant
{
public int GroupId { get; set; }
public string ParticipantId { get; set; }
public User Participant { get; set; }
public Group Group { get; set; }
}
我需要選擇用戶指定的用戶未加入的組。我想做類似的事情:
string userId = 5;
var groupsAvailableToJoin = await _context.Groups
.Where(group => group.Participants.Id != userId);
謝謝!
uj5u.com熱心網友回復:
像這樣的查詢:
_context.Groups.Where(g =>
!_context.GroupParticipants.Any(gp => gp.UserId == userId && gp.GroupId == g.I'd
);
應翻譯為:
SELECT * FROM Groups g
WHERE NOT EXISTS(SELECT null FROM groupParticipants gp WHERE gp.UserId = 5 AND gp.GroupId = g.Id)
這應該是讓您獲得所需內容的合理高效方式。我確信 GroupParticipants 列已編入索引。
有多種撰寫方法 - 如果您發現兩步方法更容易理解,它實際上與以下內容相同:
var joined = _context.GroupParticipants.Where(gp => gp.UserId == 5).Select(gp => gp.GroupId).ToList();
var notJoined = _context.Groups.Where(g => !joined.Contains(g.Id));
這個翻譯成NOT IN (list,of,groups,they,are,in)類似的效果
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/407093.html
標籤:
