加入子查询结果

时间:2013-01-22 17:42:18

标签: linq linq-to-entities

我有一个名为IssueStatuses的表和另一个名为Issues的表。问题有StatusIDSubStatusID,两者都来自IssueStatuses表,其中有一个附加字段,表明它是否为SubStatus,如下所示:

IssueStatuses

  • IssueStatusID
  • IssueStatus
  • IsSubStatus

我正在尝试获取特定问题列表的SubStatuses列表。在SQL中它是:

SELECT iss.IssueStatus, COUNT(iss.IssueStatus) AS Total
FROM Issues AS Issues 
INNER JOIN Rooms r ON Issues.RoomID = r.RoomID 
INNER JOIN Locations l ON l.LocationID = r.LocationID 
INNER JOIN Customers c ON l.CustomerID = c.CustomerID 
INNER JOIN (SELECT * FROM IssueStatuses WHERE IsSubStatus = 0) ist ON Issues.IssueStatusID = ist.IssueStatusID 
INNER JOIN (SELECT * FROM IssueStatuses WHERE IsSubStatus = 1) iss ON Issues.IssueSubStatusID = iss.IssueStatusID 
WHERE c.Customer = 'ABC' 
AND l.Location = 'MySite'
GROUP BY iss.IssueStatus

但是我无法将其转换为LINQ。所需的输出类似于:

IssueStatus | Total
-------------------
Open          15
Delayed       25
On Time       8 

这是我用LINQ试过的:

var query = from i in Issues
join r in Rooms on i.RoomID equals r.RoomID
join l in Locations on r.RoomID equals l.LocationID
join c in Customers on l.CustomerID equals c.CustomerID
where i.IssueStatusID == (from ist in IssueStatuses
                            where ist.IsSubStatus == false
                            select ist)
&& i.IssueSubStatusID == (from iss in IssueStatuses
                            where iss.IsSubStatus == true
                            select iss)
&& c.Custome == "ABC"
&& l.Location == "MySite"
    group i by i.IssueStatus

但我知道这是错误的,因为LINQPad会引发错误说明:

can't convert int to type Models.IssueStatus

我需要做的是使用iss.IssueStaus分组,但我无法访问它。有人能告诉我我做错了吗?

2 个答案:

答案 0 :(得分:1)

这个怎么样(未经测试,但我应该接近):

var query = from i in Issues
            join r in Rooms on i.RoomID equals r.RoomID
            join l in Locations on r.LocationID equals l.LocationID
            join c in Customers on l.CustomerID equals c.CustomerID
            join ist in IssueStatuses on i.IssueStatusID equals ist.IssueStatusID
            join iss in IssueStatuses on i.IssueSubStatusID equals iss.IssueStatusID
            where !ist.IsSubStatus && iss.IsSubStatus
                && c.Customer == "ABC"
                && l.Location == "MySite"
            group i by iss.IssueStatus into g
            select new {IssueStatus = g.Key, Total = g.Count()}

答案 1 :(得分:0)

您的两个内部from语句返回对象而非ID ...选择您需要的ID ist.IssueStatusID

var query = from i in Issues
join r in Rooms on i.RoomID equals r.RoomID
join l in Locations on r.RoomID equals l.LocationID
join c in Customers on l.CustomerID equals c.CustomerID
where (from ist in IssueStatuses
                            where ist.IsSubStatus == false
                            select ist.IssueStatusID).Contains(i.IssusStatusID)
&& (from iss in IssueStatuses
                            where iss.IsSubStatus == true
                            select iss.IssueStatusID).Contains(i.IssueSubStatusID)
&& c.Customer == "ABC"
&& l.Location == "MySite"
    group i by i.IssueStatus