public static QueryOver <Equipment, Equipment> AvailableEquipmentQuery() { Vodovoz.Domain.Orders.Order orderAlias = null; Equipment equipmentAlias = null; WarehouseMovementOperation operationAddAlias = null; OrderEquipment orderEquipmentAlias = null; var equipmentInStockCriterion = Subqueries.IsNotNull( QueryOver.Of <WarehouseMovementOperation>(() => operationAddAlias) .OrderBy(() => operationAddAlias.OperationTime).Desc .Where(() => equipmentAlias.Id == operationAddAlias.Equipment.Id) .Select(op => op.IncomingWarehouse) .Take(1).DetachedCriteria ); var subqueryAllReservedEquipment = QueryOver.Of <Vodovoz.Domain.Orders.Order>(() => orderAlias) .Where(() => orderAlias.OrderStatus == OrderStatus.Accepted || orderAlias.OrderStatus == OrderStatus.InTravelList || orderAlias.OrderStatus == OrderStatus.OnLoading) // чтобы не добавить в доп соглашение оборудование добавленное в уже созданный заказ. .JoinAlias(() => orderAlias.OrderEquipments, () => orderEquipmentAlias) .Where(() => orderEquipmentAlias.Direction == Direction.Deliver) .Select(Projections.Property(() => orderEquipmentAlias.Equipment.Id)); return(QueryOver.Of <Equipment>(() => equipmentAlias) .Where(equipmentInStockCriterion) .Where(e => e.AssignedToClient == null) .WithSubquery.WhereProperty(() => equipmentAlias.Id).NotIn(subqueryAllReservedEquipment)); }