使用Linq查询来计算符合条件的孙元素

时间:2013-02-06 16:45:40

标签: c# lambda linq-to-entities entity-framework-5

我正在尝试确定当前用户是否已投票ProjectDoc。此查询的值为1. ProjectDocVote表中没有与UserID匹配的值。 ViewBag.CurrentUserID值是正确的。

 var count = Model.Project.ProjectDoc
       .Where(a => a.Current == true && a.DocType == "Cover")
       .Select(v => v.ProjectDocVote
              .SingleOrDefault(u => u.UserID == ViewBag.CurrentUserID)
       )
       .Count();

如何修复此查询?

2 个答案:

答案 0 :(得分:2)

SelectSingleOrDefault替换为Any

var hasVoted = Model.Project.ProjectDoc
                    .Where(a => a.Current == true && a.DocType == "Cover")
                    .Any(v => v.ProjectDocVote
                               .Any(u => u.UserID == ViewBag.CurrentUserID));

答案 1 :(得分:1)

var count = Model.Project.ProjectDoc
   .Where(a => a.Current == true 
            && a.DocType == "Cover"
            && a.ProjectDocVote.Any(v => v.UserID == ViewBag.CurrentUserID))
   .Count():