Пример #1
0
        public IPage <Peanut> FindBilledPeanutsInGroup(IPageable pageRequest, UserGroup userGroup, DateTime?from = null, DateTime?to = null)
        {
            Require.NotNull(userGroup, "userGroup");
            Require.NotNull(pageRequest, "pageRequest");

            HibernateDelegate <IPage <Peanut> > finder = delegate(ISession session) {
                IQueryOver <Peanut, Peanut> queryOver = session.QueryOver <Peanut>();

                queryOver.JoinQueryOver <Bill>(peanut => peanut.Bills).Where(peanutBill => peanutBill.IsSettled && peanutBill.UserGroup == userGroup);
                queryOver.Where(peanut => peanut.UserGroup == userGroup);

                if (from.HasValue)
                {
                    queryOver.And(p => p.Day > from.Value);
                }

                if (to.HasValue)
                {
                    queryOver.And(p => p.Day <= to.Value);
                }

                return(FindPage(queryOver, pageRequest));
            };

            return(HibernateTemplate.Execute(finder));
        }
Пример #2
0
        void UpdateCountEntries(WordType wordType = null)
        {
            using (ISession session = DataHelper.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    Word   w = null;
                    Lesson l = null;
                    IQueryOver <Word, WordType> words =
                        session.QueryOver <Word>(() => w)
                        .JoinQueryOver(pr => pr.Entry)
                        .JoinQueryOver(pr => pr.Lesson, () => l)
                        .Where(() => l.Theme == host.CurrentTheme)
                        .JoinQueryOver(pr => w.WordType);
                    if (wordType != null)
                    {
                        words.And(() => w.WordType == wordType);
                    }

                    int count = words.RowCount();

                    TreeNodeColumn node =
                        wordType == null ?
                        (TreeNodeColumn)treeWordTypes.Nodes[0] :
                        GetNode(treeWordTypes.Nodes[0].Nodes, wordType);
                    node.FarText = count.ToString();
                }
            }
        }
Пример #3
0
        public IPage <PeanutParticipation> FindParticipationsOfUser(IPageable pageRequest, User forUser, DateTime from, DateTime to,
                                                                    IList <PeanutParticipationState> participationStates = null)
        {
            HibernateDelegate <IPage <PeanutParticipation> > finder = delegate(ISession session) {
                IQueryOver <PeanutParticipation, PeanutParticipation> queryOver = session.QueryOver <PeanutParticipation>();

                IQueryOver <PeanutParticipation, UserGroupMembership> joinUserGroupMembership =
                    queryOver.JoinQueryOver(participation => participation.UserGroupMembership);
                /*Nur für den Nutzer*/
                joinUserGroupMembership.Where(userGroupMembership => userGroupMembership.User == forUser);

                IQueryOver <PeanutParticipation, Peanut> joinPeanut = queryOver.JoinQueryOver(participation => participation.Peanut);
                joinPeanut
                /*Am oder nach dem ab Datum*/
                .And(peanut => peanut.Day >= from)
                .And(peanut => peanut.PeanutState != PeanutState.Canceled)
                /*Nicht nach dem To Datum*/
                .AndNot(peanut => peanut.Day > to);

                if (participationStates != null && participationStates.Any())
                {
                    /*Nur wenn die Teilnahme einen bestimmten Status hat.*/
                    queryOver.AndRestrictionOn(part => part.ParticipationState).IsIn(participationStates.ToArray());
                }

                return(FindPage(queryOver, pageRequest));
            };

            return(HibernateTemplate.Execute(finder));
        }
Пример #4
0
        public IPage <Bill> FindDebitorBillsForUser(IPageable pageRequest, User user, bool?isSettled)
        {
            HibernateDelegate <IPage <Bill> > finder = delegate(ISession session) {
                Require.NotNull(pageRequest, "pageRequest");
                Require.NotNull(user, "user");

                /*Mitgliedschaften des Nutzers laden, da die Rechnungen gegen die Mitgliedschaft gehen*/
                QueryOver <UserGroupMembership, UserGroupMembership> userGroupMembershipSubQuery =
                    QueryOver.Of <UserGroupMembership>().Where(mem => mem.User == user).Select(mem => mem.Id);

                /*Subquery für die Rechnungen, bei denen der Nutzer Schuldner ist*/
                IQueryOver <Bill, Bill> queryOver = session.QueryOver <Bill>();
                queryOver.Right.JoinQueryOver <BillUserGroupDebitor>(bill => bill.UserGroupDebitors)
                .WithSubquery.WhereProperty(deb => deb.UserGroupMembership)
                .In(userGroupMembershipSubQuery);

                if (isSettled.HasValue)
                {
                    queryOver.And(bill => bill.IsSettled == isSettled.Value);
                }

                queryOver = queryOver.OrderBy(bill => bill.CreatedAt).Desc;

                return(FindPage(queryOver, pageRequest));
            };

            return(HibernateTemplate.Execute(finder));
        }
Пример #5
0
        public IPage <Peanut> FindPeanutsInGroups(IPageable pageRequest, IList <UserGroup> userGroups, DateTime?from, DateTime?to)
        {
            Require.NotNull(userGroups, "userGroups");
            Require.NotNull(pageRequest, "pageRequest");

            HibernateDelegate <IPage <Peanut> > finder = delegate(ISession session) {
                IQueryOver <Peanut, Peanut> queryOver = session.QueryOver <Peanut>();

                queryOver.WhereRestrictionOn(p => p.UserGroup).IsIn(userGroups.ToList());
                if (from != null)
                {
                    /*Am oder nach dem ab Datum*/
                    queryOver.And(peanut => peanut.Day >= from);
                }
                if (to != null)
                {
                    /*Nicht nach dem To Datum*/
                    queryOver.AndNot(peanut => peanut.Day > to);
                }

                return(FindPage(queryOver, pageRequest));
            };

            return(HibernateTemplate.Execute(finder));
        }
Пример #6
0
        private IQueryOver <MyTraining, MyTraining> getMyTrainingsCriterias(IQueryOver <MyTraining, MyTraining> queryProducts, GetMyTrainingsParam param)
        {
            queryProducts = queryProducts.ApplyUser(param, Session, SecurityInfo);
            if (queryProducts == null)
            {
                return(null);
            }

            if (param.MyTrainingId.HasValue)
            {
                queryProducts = queryProducts.Where(day => day.GlobalId == param.MyTrainingId.Value);
            }
            if (param.StartDate.HasValue)
            {
                queryProducts = queryProducts.Where(day => day.StartDate >= param.StartDate);
            }
            if (param.EndDate.HasValue)
            {
                queryProducts = queryProducts.Where(day => day.StartDate <= param.EndDate);
            }


            if (param.TrainingEnds.Count > 0)
            {
                var langOr = Restrictions.Disjunction();
                foreach (var lang in param.TrainingEnds)
                {
                    langOr.Add <MyTraining>(x => x.TrainingEnd == (TrainingEnd)lang);
                }
                queryProducts = queryProducts.And(langOr);
            }

            IQueryOverOrderBuilder <MyTraining, MyTraining> orderBuilder;

            switch (param.SortOrder)
            {
            case MyTrainingSortOrder.StartDate:
                orderBuilder = queryProducts.OrderBy(x => x.StartDate);
                break;

            case MyTrainingSortOrder.PercentageCompleted:
                orderBuilder = queryProducts.OrderBy(x => x.PercentageCompleted);
                break;

            default:
                orderBuilder = queryProducts.OrderBy(x => x.Name);
                break;
            }
            if (param.SortAscending)
            {
                queryProducts = orderBuilder.Asc;
            }
            else
            {
                queryProducts = orderBuilder.Desc;
            }
            return(queryProducts);
        }
Пример #7
0
        public long CountLong <T>(params Expression <Func <T, bool> >[] where) where T : class
        {
            IQueryOver <T, T> query = session.QueryOver <T>();

            foreach (var w in where)
            {
                query = query.And(w);
            }
            return(query.RowCountInt64());
        }
Пример #8
0
        public List <KodIsim> GetCariKodsBySubeKodu(string subeKodu, string cariKodIsim, FTIRSIP ftirsip)
        {
            KodIsim kodIsim = null;
            IQueryOver <Cari, Cari> over = Session.QueryOver <Cari>().Where(x => (x.Sube.Id == subeKodu || x.SubelerdeOrtak == true) &&
                                                                            (x.Id.IsLike(cariKodIsim, MatchMode.Anywhere) || x.CariIsim.IsLike(cariKodIsim, MatchMode.Anywhere)));

            if (FTIRSIP.AlisFat == ftirsip || FTIRSIP.AlisIrs == ftirsip)
            {
                over.And(x => (x.CariTip == "S" || x.CariTip == "AS"));
            }
            else if (FTIRSIP.SatisFat == ftirsip || FTIRSIP.SatisIrs == ftirsip)
            {
                over.And(x => (x.CariTip == "A" || x.CariTip == "AS"));
            }
            return(over.SelectList(liste =>
                                   liste.SelectGroup(c => c.Id).WithAlias(() => kodIsim.Kod)
                                   .SelectGroup(c => c.CariIsim).WithAlias(() => kodIsim.Isim)
                                   ).TransformUsing(Transformers.AliasToBean <KodIsim>())
                   .Take(GetMaxResult).List <KodIsim>() as List <KodIsim>);
        }
Пример #9
0
        /// <summary>
        /// And
        /// </summary>
        /// <param name="source"><see cref="IQueryOver{TRoot}"/></param>
        /// <param name="expressions"><see cref="IList{T}"/></param>
        /// <typeparam name="T"></typeparam>
        /// <returns><see cref="IQueryOver{TRoot}"/></returns>
        public static IQueryOver <T, T> And <T>(this IQueryOver <T, T> source, IList <Expression <Func <T, bool> > > expressions)
        {
            if (expressions != null && expressions.Any())
            {
                foreach (var expression in expressions)
                {
                    source.And(expression);
                }
            }

            return(source);
        }
Пример #10
0
        /// <summary>
        /// And
        /// </summary>
        /// <param name="source"><see cref="IQueryOver{TRoot}"/></param>
        /// <param name="criterions"><see cref="IList{T}"/></param>
        /// <typeparam name="T"></typeparam>
        /// <returns><see cref="IQueryOver{TRoot}"/></returns>
        public static IQueryOver <T, T> And <T>(this IQueryOver <T, T> source, IList <ICriterion> criterions)
        {
            if (criterions != null && criterions.Any())
            {
                foreach (var criterion in criterions)
                {
                    source.And(criterion);
                }
            }

            return(source);
        }
Пример #11
0
        public IQueryOver <Entry> Entries(Theme theme, Lesson lesson)
        {
            IQueryOver <Entry, Lesson> query = Session.QueryOver <Entry>()
                                               .JoinQueryOver(pr => pr.Lesson)
                                               .Where(x => x.Theme == theme);

            if (lesson != null)
            {
                query = query.And(x => x.Id == lesson.Id);
            }

            return(query);
        }
Пример #12
0
        /// <summary>
        /// Vengono filtrate le workflow activity ai quali l'utente ha diritto:
        /// </summary>
        private IQueryOver <WorkflowActivity, WorkflowActivity> FilterByUserPermission(IQueryOver <WorkflowActivity, WorkflowActivity> queryOver)
        {
            try
            {
                if (!string.IsNullOrEmpty(_currentUserName))
                {
                    DetachedCriteria dCriteria = DetachedCriteria.For <WorkflowAuthorization>().Add(
                        Restrictions.Where <WorkflowAuthorization>(wa => wa.Account == _currentUserName && wa.WorkflowActivity.Id == workflowActivityAlias.Id))
                                                 .SetProjection(Projections.Property <WorkflowAuthorization>(wa => wa.Id));

                    queryOver.And(Restrictions.Or(
                                      Restrictions.Where <WorkflowActivity>(wa => wa.RegistrationUser == RequestorUser),
                                      Subqueries.Exists(dCriteria)));
                }
            }
            catch (Exception ex)
            {
                throw new DocSuiteException("Errore in FilterByUserPermission", ex);
            }
            return(queryOver);
        }
Пример #13
0
        public IPage <Bill> FindPendingBillsByUser(IPageable pageRequest, User user)
        {
            Require.NotNull(pageRequest, "pageRequest");
            Require.NotNull(user, "user");

            HibernateDelegate <IPage <Bill> > finder = delegate(ISession session) {
                QueryOver <UserGroupMembership, UserGroupMembership> userGroupMembershipSubQuery =
                    QueryOver.Of <UserGroupMembership>().Where(mem => mem.User == user).Select(mem => mem.Id);

                /*Subquery für die Rechnungen, bei denen der Nutzer Schuldner ist*/
                QueryOver <BillUserGroupDebitor, BillUserGroupDebitor> debitorSubQuery =
                    QueryOver.Of <BillUserGroupDebitor>().WithSubquery.WhereProperty(deb => deb.UserGroupMembership).In(userGroupMembershipSubQuery).Select(deb => deb.Id);
                IList <BillUserGroupDebitor> userGroupAlias       = null;
                QueryOver <Bill, Bill>       debitorBillsSubquery =
                    QueryOver.Of <Bill>()
                    .JoinAlias(bill => bill.UserGroupDebitors, () => userGroupAlias)
                    .WithSubquery.WhereProperty(bill => bill.Creditor).In(debitorSubQuery)
                    .Select(bill => bill.Id);

                /*Subquery für die Rechnungen, bei denen der Nutzer Gläubiger ist*/
                QueryOver <Bill, Bill> creditorSubQuery =
                    QueryOver.Of <Bill>().WithSubquery.WhereProperty(bill => bill.Creditor).In(userGroupMembershipSubQuery).Select(bill => bill.Id);

                /*Nur Rechnungen, die die Subqueries erfüllen*/
                IQueryOver <Bill, Bill> queryOver = session.QueryOver <Bill>();
                queryOver
                .Where(Restrictions.Disjunction()
                       .Add(Subqueries.WhereProperty <Bill>(x => x.Id).In(debitorBillsSubquery))
                       .Add(Subqueries.WhereProperty <Bill>(x => x.Id).In(creditorSubQuery)));

                /*Rechnung muss offen sein.*/
                queryOver.And(bill => bill.IsSettled == false);

                return(FindPage(queryOver, pageRequest));
            };

            return(HibernateTemplate.Execute(finder));
        }
        private static IQueryOver <SupplementCycleDefinition, SupplementCycleDefinition> getSupplementsCycleDefinitionsCriterias(GetSupplementsCycleDefinitionsParam param, Profile loggedProfile, List <Guid> ids, Profile myProfile,
                                                                                                                                 IQueryOver <SupplementCycleDefinition, SupplementCycleDefinition> queryCustomer)
        {
            SupplementCycleDosage dosage = null;
            SupplementCycleWeek   week   = null;

            queryCustomer = queryCustomer.JoinAlias(x => x.Weeks, () => week)
                            .JoinAlias(x => x.Weeks.First().Dosages, () => dosage);

            if (param.LegalCriteria == CanBeIllegalCriteria.OnlyLegal)
            {
                queryCustomer = queryCustomer.Where(x => !x.CanBeIllegal);
            }
            else if (param.LegalCriteria == CanBeIllegalCriteria.OnlyIllegal)
            {
                queryCustomer = queryCustomer.Where(x => x.CanBeIllegal);
            }

            if (param.PlanId.HasValue)
            {
                queryCustomer = queryCustomer.Where(x => x.GlobalId == param.PlanId.Value);
            }
            if (param.Languages.Count > 0)
            {
                var langOr = Restrictions.Disjunction();
                foreach (var lang in param.Languages)
                {
                    langOr.Add <SupplementCycleDefinition>(x => x.Language == lang);
                }
                queryCustomer = queryCustomer.And(langOr);
            }
            if (param.Purposes.Count > 0)
            {
                var purposeOr = Restrictions.Disjunction();
                foreach (var purpose in param.Purposes)
                {
                    purposeOr.Add <SupplementCycleDefinition>(x => x.Purpose == (WorkoutPlanPurpose)purpose);
                }
                queryCustomer = queryCustomer.And(purposeOr);
            }
            if (param.Difficults.Count > 0)
            {
                var mainOr = Restrictions.Disjunction();
                foreach (TrainingPlanDifficult diff in param.Difficults)
                {
                    var tt = (BodyArchitect.Model.TrainingPlanDifficult)diff;
                    mainOr.Add <SupplementCycleDefinition>(x => x.Difficult == tt);
                }
                queryCustomer = queryCustomer.And(mainOr);
            }

            if (param.Supplements.Count > 0)
            {
                Junction supplementsOperations = null;
                if (param.SupplementsListOperator == CriteriaOperator.Or)
                {
                    supplementsOperations = Restrictions.Disjunction();
                    foreach (var supplementId in param.Supplements)
                    {
                        supplementsOperations.Add <SupplementCycleDefinition>(x => dosage.Supplement.GlobalId == supplementId);
                    }
                }
                else
                {
                    supplementsOperations = Restrictions.Conjunction();
                    foreach (var supplementId in param.Supplements)
                    {
                        var orderIdsCriteria = DetachedCriteria.For <SupplementCycleDosage>();
                        orderIdsCriteria.SetProjection(Projections.CountDistinct("GlobalId"))
                        .Add(Restrictions.Where <SupplementCycleDosage>(x => x.Supplement.GlobalId == supplementId))
                        .Add(Restrictions.Where <SupplementCycleDosage>(x => x.Week.GlobalId == week.GlobalId));

                        supplementsOperations.Add(Subqueries.Lt(0, orderIdsCriteria));
                        //supplementsOperations.Add<SupplementCycleDosage>(x => dosage.Supplement.GlobalId == supplementId);
                    }
                }
                queryCustomer = queryCustomer.And(supplementsOperations);
            }

            queryCustomer = queryCustomer.Where(x => x.Profile == loggedProfile || (x.Profile != loggedProfile && x.Status == PublishStatus.Published));

            var groupOr = new Disjunction();

            if (param.SearchGroups.Count > 0)
            {
                if (param.SearchGroups.IndexOf(WorkoutPlanSearchCriteriaGroup.Mine) > -1)
                {
                    groupOr.Add <BodyArchitect.Model.SupplementCycleDefinition>(x => x.Profile == myProfile);
                }
                if (param.SearchGroups.IndexOf(WorkoutPlanSearchCriteriaGroup.Favorites) > -1)
                {
                    if (myProfile.FavoriteSupplementCycleDefinitions.Count > 0)
                    {
                        groupOr.Add <BodyArchitect.Model.SupplementCycleDefinition>(x => x.GlobalId.IsIn((ICollection)ids));
                    }
                }
                if (param.SearchGroups.IndexOf(WorkoutPlanSearchCriteriaGroup.Other) > -1)
                {
                    var tmpAnd = Restrictions.Conjunction();
                    tmpAnd.Add <BodyArchitect.Model.SupplementCycleDefinition>(
                        dto => dto.Profile != null && dto.Profile != myProfile);

                    if (ids.Count > 0)
                    {
                        tmpAnd.Add(Restrictions.On <BodyArchitect.Model.SupplementCycleDefinition>(x => x.GlobalId).Not.IsIn((ICollection)ids));
                    }

                    groupOr.Add(tmpAnd);
                }
                queryCustomer = queryCustomer.Where(groupOr);
            }
            return(queryCustomer);
        }
Пример #15
0
        public IQueryOver <NodeVersion, NodeVersionStatusHistory> GenerateVersionedQuery(out NodeVersion outerVersionSelectAlias, Guid[] nodeIds = null, RevisionStatusType revisionStatus = null, bool limitToLatestRevision = true)
        {
            // We want the NodeVersion table, joined to the NodeVersionStatusHistory table,
            // ordered by the status history date descending, but we only want the latest one

            Node        node             = null;
            NodeVersion subSelectVersion = null;
            NodeVersionStatusHistory subSelectTopStatus = null;
            NodeVersion           outerVersionSelect    = null;
            NodeVersionStatusType subSelectStatusType   = null;

            // First define the subselection of the top 1 version items when joined and sorted by version status history in date-descending order
            // We also add a clause to say "where the outer selected version's node id equals the subselected node id" since it's selecting the top 1
            // so we want it to be the 1 latest-date item relevant for each row of the outer select
            var subSelectTopStatusByDate = QueryOver.Of(() => subSelectTopStatus)
                                           //.Where(() => subSelectTopStatus.NodeVersion.Id == outerVersionSelect.Id);
                                           .JoinQueryOver(() => subSelectTopStatus.NodeVersion, () => subSelectVersion)
                                           .JoinQueryOver(() => subSelectVersion.Node, () => node)
                                           .Where(() => subSelectTopStatus.NodeVersion.Id == subSelectVersion.Id)
                                           .And(() => outerVersionSelect.Node.Id == node.Id);

            int takeCount = limitToLatestRevision ? 1 : 999;

            // Now we need to add a filter for the revision status type, if one was supplied
            QueryOver <NodeVersionStatusHistory> subSelectTopStatusByDateWithFilter = null;
            QueryOver <NodeVersionStatusHistory> excludeNegatingStatusses           = null;

            if (revisionStatus != null)
            {
                var statusAlias = revisionStatus.Alias;

                if (revisionStatus.NegatedByTypes.Any())
                {
                    NodeVersionStatusHistory negateHistory = null;
                    NodeVersionStatusType    negateType    = null;
                    NodeVersion negateVersion   = null;
                    var         negatingAliases = revisionStatus.NegatedByTypes.Select(x => x.Alias).ToArray();

                    //var first = negatingAliases.First();
                    excludeNegatingStatusses = QueryOver.Of(() => negateHistory)
                                               .JoinAlias(() => negateHistory.NodeVersionStatusType, () => negateType)
                                               .JoinAlias(() => negateHistory.NodeVersion, () => negateVersion)
                                               .Where(() => negateType.Alias.IsIn(negatingAliases))
                                               .And(() => outerVersionSelect.Node == negateVersion.Node)
                                               .Select(Projections.SqlFunction("coalesce", NHibernateUtil.DateTime, Projections.Max <NodeVersionStatusHistory>(x => x.Date), new ConstantProjection(new DateTime(1981, 8, 1))));

                    //excludeNegatingStatusses = QueryOver.Of(() => negateHistory)
                    //    .JoinAlias(() => negateHistory.NodeVersionStatusType, () => negateType)
                    //    .JoinAlias(() => negateHistory.NodeVersion, () => negateVersion)
                    //    .JoinAlias(() => negateVersion.Node, () => node)
                    //    .Where(() => negateType.Alias.IsIn(negatingAliases))
                    //    .And(() => negateHistory.Date > subSelectTopStatus.Date)
                    //    //.And(() => subSelectTopStatus.NodeVersion.Id == negateVersion.Id)
                    //    .And(() => outerVersionSelect.Node.Id == node.Id)
                    //    .Select(x => x.Id)
                    //    .Take(1);

                    //excludeNegatingStatusses = QueryOver.Of(() => negateHistory)
                    //    .JoinAlias(() => negateHistory.NodeVersionStatusType, () => negateType)
                    //    .JoinAlias(() => negateHistory.NodeVersion, () => negateVersion)
                    //    .JoinAlias(() => negateVersion.Node, () => node)
                    //    .Where(() => negateType.Alias.IsIn(negatingAliases))
                    //    .And(() => outerVersionSelect.Node.Id == node.Id)
                    //    .And(() => negateHistory.Date > subSelectTopStatus.Date)
                    //    .OrderBy(x => x.Date).Desc
                    //    .Select(x => x.Id)
                    //    .Take(1);
                }

                var subSelectBuilder = subSelectTopStatusByDate
                                       .And(() => subSelectStatusType.Alias == statusAlias)
                                       .JoinQueryOver(x => subSelectTopStatus.NodeVersionStatusType, () => subSelectStatusType)
                                       .OrderBy(() => subSelectTopStatus.Date).Desc;

                if (excludeNegatingStatusses != null)
                {
                    // Yeah, I know, horrible to check Sql dialect when generating query, but Nh's dialect support doesn't allow a provider-based
                    // way of telling whether the db engine supports / requires "all" to be prefix before a subquery when doing an operation.
                    // e.g. SqlCe requires "blah > all (select max(blah) from blah)", SqlServer doesn't mind, SQLite doesn't support it
                    if (RequiresAllForGtSubquery())
                    {
                        subSelectBuilder = subSelectBuilder.WithSubquery.WhereProperty(() => subSelectTopStatus.Date).GtAll(excludeNegatingStatusses);
                    }
                    else
                    {
                        subSelectBuilder = subSelectBuilder.WithSubquery.WhereProperty(() => subSelectTopStatus.Date).Gt(excludeNegatingStatusses);
                    }

                    //subSelectBuilder = subSelectBuilder.WithSubquery.WhereNotExists(excludeNegatingStatusses);
                    //subSelectBuilder = subSelectBuilder.WithSubquery.WhereProperty(() => subSelectTopStatus.Id).NotIn(excludeNegatingStatusses);
                }

                subSelectTopStatusByDateWithFilter = subSelectBuilder.Select(x => subSelectTopStatus.NodeVersion.Id).Take(takeCount);
                // We have to include a Take here for compatibility with SqlServerCe
            }
            else
            {
                subSelectTopStatusByDateWithFilter = subSelectTopStatusByDate
                                                     .OrderBy(() => subSelectTopStatus.Date).Desc
                                                     .Select(x => subSelectTopStatus.NodeVersion.Id).Take(takeCount);
                // We have to include a Take here for compatibility with SqlServerCe
            }

            NodeVersionStatusHistory outerHistoryForSort = null;
            IQueryOver <NodeVersion, NodeVersionStatusHistory> outerQuery = NhSession.QueryOver <NodeVersion>(
                () => outerVersionSelect)
                                                                            //.Fetch(x => x.AttributeSchemaDefinition).Eager
                                                                            .Fetch(x => x.Attributes).Eager
                                                                            // We load these eagerly rather than in a Future to avoid a separate query
                                                                            .Fetch(x => x.Node).Eager
                                                                            // There's a 1-m mapping between Node-NodeVersion so safe to load this with a join too rather than with a future
                                                                            .Inner.JoinQueryOver(x => outerHistoryForSort.NodeVersionStatusType, () => subSelectStatusType)
                                                                            .Inner.JoinQueryOver(x => outerVersionSelect.NodeVersionStatuses, () => outerHistoryForSort);

            NodeVersion innerVersion = null;
            NodeVersionStatusHistory innerHistory = null;
            NodeVersionStatusType    innerType    = null;
            var buildInnerHistorySubQuery         = QueryOver.Of <NodeVersionStatusHistory>(() => innerHistory)
                                                    .JoinQueryOver(() => innerHistory.NodeVersion, () => innerVersion)
                                                    .JoinQueryOver(() => innerHistory.NodeVersionStatusType, () => innerType)
                                                    .Where(() => innerVersion.Node == outerVersionSelect.Node);

            if (revisionStatus != null)
            {
                var statusAlias = revisionStatus.Alias;
                buildInnerHistorySubQuery = buildInnerHistorySubQuery
                                            .And(() => innerType.Alias == statusAlias);

                NodeVersionStatusType reselectType = null;
                outerQuery = outerQuery
                             .And(() => subSelectStatusType.Alias == statusAlias);

                // Yeah, I know, horrible to check Sql dialect when generating query, but Nh's dialect support doesn't allow a provider-based
                // way of telling whether the db engine supports / requires "all" to be prefix before a subquery when doing an operation.
                // e.g. SqlCe requires "blah > all (select max(blah) from blah)", SqlServer doesn't mind, SQLite doesn't support it
                if (excludeNegatingStatusses != null)
                {
                    if (RequiresAllForGtSubquery())
                    {
                        outerQuery = outerQuery.WithSubquery.WhereProperty(() => outerHistoryForSort.Date).GtAll(excludeNegatingStatusses);
                    }
                    else
                    {
                        outerQuery = outerQuery.WithSubquery.WhereProperty(() => outerHistoryForSort.Date).Gt(excludeNegatingStatusses);
                    }
                }
            }

            var subQueryInnerHistory = buildInnerHistorySubQuery.Select(x => x.Id)
                                       .OrderBy(() => innerHistory.Date).Desc
                                       .Take(takeCount);

            outerQuery = outerQuery
                         .OrderBy(() => outerHistoryForSort.Date).Asc
                         .WithSubquery.WhereProperty(() => outerHistoryForSort.Id).In(subQueryInnerHistory);

            //// Based on perf testing of SqlCe queries, it shaves a lot off execution time if we specify the status type in the
            //// outer query in addition to the subquery
            //if (revisionStatus != null)
            //{
            //    var statusAlias = revisionStatus.Alias;
            //    outerQuery = outerQuery
            //        .And(x => subSelectStatusType.Alias == statusAlias);
            //}

            //outerQuery = outerQuery
            //    .OrderBy(() => outerHistoryForSort.Date).Asc
            //    .WithSubquery.WhereProperty(() => outerVersionSelect.Id).In(subSelectTopStatusByDateWithFilter.Clone());

            if (nodeIds != null && nodeIds.Any())
            {
                outerQuery = outerQuery.And(() => outerVersionSelect.Node.Id.IsIn(nodeIds));
            }

            outerVersionSelectAlias = outerVersionSelect;
            return(outerQuery);
        }
Пример #16
0
 public IQueryBuilder <T> And(Expression <Func <T, bool> > expression)
 {
     _query.And(expression);
     return(this);
 }
 public IQueryOver <TRoot, TSubType> And(Expression <Func <TSubType, bool> > expression)
 {
     MainQuery.And(expression);
     return(this);
 }
Пример #18
0
 public void Builder <TE, TSe>(IQueryOver <TE, TSe> queryOver)
 {
     queryOver.And(_predicateCriterion);
 }