2017-08-22 50 views
1

我有一個表:LINQ編譯的查詢選擇和多列

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

給定一個ObjectTypeIDObjectID,我想返回Tuple<int, int, int>其中相應的值是:

  • 總票數:其中ShadowBannedVote == false
  • 總記錄數:的記錄總數,其中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))); 

回答

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))); 

,然後只需在應用程序邏輯制定出號。

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());