[英]Assign COUNT() to model field when projecting into a Model
我有2个表希望加入其中并从中建立模型: Issues
和IssueAttachments
。 模型中的字段之一是每个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
错误Unable to create a constant value of type
。 我在SO周围寻找了一些示例,但是由于缺乏对linq的了解,我不得不在大多数情况下挠头。
任何帮助是极大的赞赏。
您可以尝试以下一种方法:
// 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
};
注意
如果您需要在更多字段中获取附件的值,则必须首先按照我们在组中进行选择。 请让我知道,以便更新我的帖子。 谢谢。
var result = db.Issues
.GroupJoin
(
db.IssueAttachments ,
x=>x.IssueID ,
x=>x.IssueID ,
(i,ia)=>new
{
i.IssueID,
/*** more fields ***/
NumberOfAttachments = ia.Count()
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.