使用LINQ lambda表达式在导航表中选择通用值
本文关键字:选择 导航 LINQ lambda 表达式 使用 | 更新日期: 2023-09-27 18:08:29
我有一个名为InvestigatorGroup
的表和一个名为InvestigatorGroupUsers
的表,用于查看哪些组拥有哪些用户。我正在尝试获得两个用户之间的共同调查员组
我的查询如下:
public InvestigatorGroup GetCommonGroup(string userId, string investigatorUserId)
{
using (GameDbContext entityContext = new GameDbContext())
{
string[] ids = new[] { userId, investigatorUserId };
return entityContext.InvestigatorGroups
.Where(i => i.IsTrashed == false)
.Include(i => i.InvestigatorGroupUsers)
.Where(i => i.InvestigatorGroupUsers.Any(e => ids.Contains(e.UserId)))
.OrderByDescending(i => i.InvestigatorGroupId)
.GroupBy(i => i.InvestigatorGroupId)
.Where(i => i.Count() > 1)
.SelectMany(group => group).FirstOrDefault();
}
}
实体InvestigatorGroup如下:
public class InvestigatorGroup : IIdentifiableEntity
{
public InvestigatorGroup()
{
this.InvestigatorGroupGames = new HashSet<InvestigatorGroupGame>();
this.InvestigatorGroupUsers = new HashSet<InvestigatorGroupUser>();
}
// Primary key
public int InvestigatorGroupId { get; set; }
public string InvestigatorGroupName { get; set; }
public bool HasGameAssignment { get; set; }
public string GroupRoleName { get; set; }
public bool IsTrashed { get; set; }
// Navigation property
public virtual ICollection<InvestigatorGroupUser> InvestigatorGroupUsers { get; private set; }
public virtual ICollection<InvestigatorGroupGame> InvestigatorGroupGames { get; private set; }
public int EntityId
{
get { return InvestigatorGroupId; }
set { InvestigatorGroupId = value; }
}
}
问题是它一直返回0的值。它看不到两个用户之间计数为2的共享组。
我做了一个测试来返回组(我删除了count>1条件),它返回了两个用户的所有组,而不仅仅是他们共有的组
我认为问题出在这一行:.Where(i => i.InvestigatorGroupUsers.Any(e => ids.Contains(e.UserId)))
谢谢你的帮助!
我通过更改查询来解决这个问题,以便它搜索包含UserId之一的行。然后,它查询这些选定的行,并选择包含另一个UserId (InvestigatorUserId)的行。这样,只返回包含这两个元素的行
我的新代码如下: public InvestigatorGroup GetCommonGroup(string userId, string investigatorUserId)
{
using (GameDbContext entityContext = new GameDbContext())
{
IEnumerable<InvestigatorGroup> userGroups = entityContext.InvestigatorGroups
.Where(i => i.IsTrashed == false)
.Include(i => i.InvestigatorGroupUsers)
.Where(i => i.InvestigatorGroupUsers.Any(e => e.UserId.Contains(userId)))
.OrderByDescending(i => i.InvestigatorGroupId);
return userGroups.Where(i => i.InvestigatorGroupUsers.Any(e => e.UserId.Contains(investigatorUserId))).FirstOrDefault();
}
}