我正在尝试获取数据库中具有重复所有者的所有项目。我的第一个方法返回它们的计数并且可以正常工作:
public int GetUsersWithMultipleItemsCount()
{
return GetItemsSecureAsync().Result
.Where(item => item.OwnerId != null)
.GroupBy(item => item.OwnerId)
.Count(grouping => grouping.Count() > 1);
}
但是实际获取它们列表的方法无法翻译:
public IEnumerable<IGrouping<Guid?, ItemType>> GetItemsWithDuplicateOwners()
{
return GetItemsSecureAsync().Result
.Where(item => item.OwnerId != null)
.GroupBy(item => item.OwnerId)
.Where(grouping => grouping.Count() > 1)
.ToList();
}
如何修改它以使其工作而不需要客户端评估?我不想因为这样微不足道的功能而减慢我的应用程序的速度。
编辑:我虽然该解决方案有效,但现在尽管有 SelectMany 子句,但它再次失败。我为此目的创建了一个小扩展函数:
public static IQueryable<T> NonDistinct<T, TKey>(this IQueryable<T> source, Expression<Func<T, TKey>> keySelector)
{
return source.GroupBy(keySelector).Where(g => g.Count() > 1).SelectMany(r => r);
}
EF Core7 似乎存在与此相关的问题:https://github.com/dotnet/efcore/issues/28002
失败是因为
ToList()
先使用
SelectMany()
public IEnumerable<ItemType> GetItemsWithDuplicateOwners()
{
var duplicates = GetItemsSecureAsync().Result
.Where(item => item.OwnerId != null)
.GroupBy(item => item.OwnerId)
.Where(grouping => grouping.Count() > 1);
var query = duplicates.SelectMany(grouping => grouping);
return query.ToList();
}