投影到模型时,将COUNT()分配给模型字段

时间:2014-09-17 14:00:52

标签: c# linq linq-to-entities

我有2个表格,我希望加入并制作模型:IssuesIssueAttachments。模型中的一个字段是每个Issue的所有IssueAttachments的计数。在SQL中,它很简单:

SELECT i.*, 
       ISNULL
       (
           (Select COUNT(IssueID) FROM IssueAttachments WHERE IssueID = i.IssueID),
           0
       ) AS 'Number of Attachments'
FROM Issues

但我很难将其转换为linq。这是我的陈述:

var issues = from i in db.Issues
    join ia in db.IssueAttachments
    on i.IssueID equals ia.IssueID into issAttachments
    from issueAttachments in issAttachments.DefaultIfEmpty()
    select new IssueModel
    {
      IssueID = i.IssueID,
      /*** more fields ***/
      NumberOfAttachments = ???
    }

???是我需要为每个问题计算IssueAttachments的地方。我试过这个:

(from ia in db.IssueAttachments
 where ia.IssueID == i.IssueID
 select ia).Count()

但我收到Unable to create a constant value of type错误。我查看了一些例子,但是我缺乏linq知识让我对大多数人感到头疼。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

你可以尝试这个:

// Initially, we make a group of all the issue attachments based on the IssueID
// and we count the corresponding number of attachments.

var attachments = db.IssueAttachments
                    .GroupBy(x=>x.IssueID)
                    .Select(x=> new { IssueID = x.Key, 
                                      NumberOfAttachments = x.Count()
                    });

然后

// Later we join the Issues tables rows with attachments results based on the IssueID
// and we select the corresponding data
var issues = from i in db.Issues
             join a in attachments
             on i.IssueID equals a.IssueID
             select new IssueModel
             {
                 IssueID = i.IssueID,
                 /*** more fields ***/
                 NumberOfAttachments = a.NumberOfAttachments
             };

<强>注意

如果您需要在更多字段中获取附件的值,您必须在我们最初的组中选择它们。请让我知道,以便更新我的帖子。感谢。

答案 1 :(得分:0)

var result = db.Issues
      .GroupJoin
      (
          db.IssueAttachments ,
          x=>x.IssueID ,
          x=>x.IssueID ,
          (i,ia)=>new
          {
              i.IssueID,
              /*** more fields ***/
              NumberOfAttachments = ia.Count()
          }
      );