I've been trying to get the following SQL
SELECT *
FROM dbo.VirtualMachines vm
WHERE vm.SequenceId IN (
SELECT MAX(SequenceId) FROM dbo.VirtualMachines GROUP BY RequestId
)
AND vm.DeletedBy IS NULL
...into a LINQ-query for use with NHibernate.
I've been able to get a variation on this working which is based on a corrolated sub-query:
var allvms = from vms in this.currentSession.Query<Entities.VirtualMachine>()
where vms.DeletedBy == null
where vms.Id == (
from activeVms in this.currentSession.Query<Entities.VirtualMachine>()
where activeVms.RequestId == vms.RequestId
orderby activeVms.Id descending
select activeVms.Id).First()
orderby vms.RequestId
select vms;
...which gives me...
SELECT *
FROM dbo.VirtualMachines vm
WHERE vm.SequenceId IN (
SELECT TOP 1 zvm.SequenceId From dbo.VirtualMachines zvm WHERE zvm.RequestId = vm.RequestId ORDER BY zvm.SequenceId DESC
)
AND vm.DeletedBy IS NULL
...however I'd rather use the MAX()
version as (having profiled SQL Server) it's a more efficient query for the dataset I'm working with. Unfortunatly, I can't work out how to wrangle LINQ to give me the query.
I know I can do:
from vms in this.currentSession.Query<Entities.VirtualMachine>()
group vms by vms.RequestId into vmReqs
select new {
LatestSeqId = vmReqs.Max(vms => vms.SequenceId)
}
which gives me the sub-select (SELECT MAX(SequenceId) [...]
), but I can't see how to combine this with the query I've already got to do an IN
. It's possible I'm approaching this in too-SQL a mindset, and I'm trying to approach the query as I would in SQL and there's some other technique I've missed.