我有一个查询,如果我运行得到以下结果:
查询:
SELECT FROM Ticket WHERE ClosedOn IS NULL AND AssignedToTeamID = 1 AND TicketPriorityID = 2
结果:
现在我们想要的是以下查询:
查询:
SELECT DISTINCT ServerID, SiteID,
Case when(DetectorID-DetectorID%10) not in
(Select Distinct SiteID FROM Ticket
where SiteID is not NULL
and ClosedOn is null
and AssignedToTeamID = 1
and TicketPriorityID in (1, 2))
THEN DetectorID-DetectorID%10
end as DetectorID
FROM Ticket
where ClosedOn is null
and AssignedToTeamID = 1
and TicketPriorityID in (1, 2)
现在,这是我想要的结果(不知道为什么第一个结果是NULL,NULL,NULL)。但现在这并不重要。
我的问题:
如何在我的代码中获取查询?
我现在拥有的(第一个查询中的结果):
User user = ObjectContext.Users
.Include("TeamMemberships")
.First(u => u.UserID == userID);
var teamIDs = user.TeamMemberships.Select(t => t.TeamID).ToList();
var test = ObjectContext.Tickets
.Include("TicketPriority")
.Include("TicketStatu")
.Include("TicketType")
.Include("Server")
.Include("Site")
.Include("Detector")
.Include("Detector.Site")
.Include("Detector.Track")
.Include("Team")
.Include("User")
.Include("User1")
.Where(t => (withinTeam.HasValue ? withinTeam.Value ? teamIDs.Contains((int)t.AssignedToTeamID) : !teamIDs.Contains((int)t.AssignedToTeamID) : true))
.Where(t => t.ClosedOn == null)
.Where(t => t.TicketPriorityID == 1 || t.TicketPriorityID == 2);
return test;
我不知道如何将case / if语句放在这里。
答案 0 :(得分:0)
这样的事情:
ctx.Tickets
.Where(t => t.ClosedOn == null &&
t.AssignedToTeamId == 1 &&
(t.TicketPriorityId == 1 || t.TicketPriorityId == 2))
.Select(t => new
{
t.ServerId, t.SiteId,
DetectorId = t.DetectorId - t.DetectorId % 10
})
.Select(x => new
{
x.ServerId, x.SiteId,
DetectorId = ctx.Tickets
.Where(t => t.SiteId != null && t.ClosedOn == null &&
t.AssignedToTeamId == 1 &&
(t.TicketPriorityId == 1 || t.TicketPriorityId == 2))
.Any(t => t.Id == x.DetectorId) ?
(int?) null : x.DetectorId
})
.ToArray();
如果您需要将其与Include
结合使用,那么最好的方法是选择您需要的行ID(我假设该数字很小),之后再使用includes和t => ids.Contains(t.Id)
执行一次查询。或者您甚至可以将其作为子查询放在Where
中。最后一种方法是使用手动连接(如果您需要两者,可能需要它们:自定义计算字段和简单连接字段)。