LINQ编译查询选择和多列

时间:2017-08-22 14:25:29

标签: c# asp.net linq-to-sql compiled-query

我有一张桌子:

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

鉴于ObjectTypeIDObjectID,我希望返回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)));

2 个答案:

答案 0 :(得分: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)));

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

答案 1 :(得分: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());