2017-08-22 29 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());