1

我有一张桌子:

ForObjectTypeID (short, PK)
ForObjectID (int, PK)
UserID (int, PK)
Upvote (bool)
ShadowBannedVote (bool)

给定一个ObjectTypeIDand ObjectID,我希望返回一个Tuple<int, int, int>各自的值是:

  • 总投票数:记录的总数ShadowBannedVote == false
  • Total Upvotes:记录总数Upvote == true && ShadowBannedVote == false
  • 影子禁止投票总数:记录的总数ShadowBannedVote == true

它需要是单个编译查询,而不是分解为多个查询。据我所知,我只是无法弄清楚如何在返回值中执行总和和计数。

public static readonly Func<DBContext, ObjectType, int, Tuple<int, int, int>> GetTotalVotes = CompiledQuery.Compile(
    (DBContext db, ObjectType forObjectType, int forObjectID) =>
    db.UserVotes.Where(c => c.ForObjectTypeID == (short)forObjectType && c.ForObjectID == forObjectID)
    .Select(c=> new {c.Upvote, c.ShadowBannedVote}).Select(c=> new Tuple<int, int, in>(0, 0, 0)));
4

2 回答 2

0

您可以尝试按常数分组,求和并取结果,即类似

  public static readonly Func<DBContext, ObjectType, int, Tuple<int, int, int>> GetTotalVotes = CompiledQuery.Compile(
        (DBContext db, ObjectType forObjectType, int forObjectID) 
   => 
   db.UserVotes
    .Where(c => c.ForObjectTypeID == (short)forObjectType 
             && c.ForObjectID == forObjectID)
    .Select(c => new { c.Upvote, c.ShadowBannedVote })
    .GroupBy(c => 1)
    .Select(c => new Tuple<int, int, int>(
        c.Count(r => !r.ShadowBannedVote), 
        c.Count(r => r.Upvote && !r.ShadowBannedVote), 
        c.Count(r => r.ShadowBannedVote)
    )).Single());
于 2017-08-23T08:36:26.737 回答
0

有兴趣看看这是否可能,但一种解决方案是:

public static readonly Func<DBContext, ObjectType, int, IEnumerable<Tuple<bool, bool>>> GetTotalVotes = CompiledQuery.Compile(
    (DBContext db, ObjectType forObjectType, int forObjectID) =>
    db.UserVotes.Where(c => c.ForObjectTypeID == (short)forObjectType && c.ForObjectID == forObjectID)
    .Select(c=> new Tuple<bool, bool>(c.Upvote, c.ShadowBannedVote)));

然后简单地计算出应用程序逻辑中的数字。

于 2017-08-22T14:32:15.393 回答