public async Task <IPage <TEntity> > FindAsync(Expression <Func <TEntity, bool> > filter = null,
                                                IPageable <TEntity> pageable = null)
 {
     return(await OnFindAsync(
                filter ?? QueryExpressionHelper.True <TEntity>(),
                pageable ?? new Pageable <TEntity>(0, _settings.PageSize)
                ));
 }
        public QueryModel LoadFromStoreQuery(IQueryModel qm, StoreQuery q)
        {
            var result = new QueryModel();

            // read parameters
            result.StoreParameters.DataService     = q.DataService;
            result.StoreParameters.QueryName       = q.Name;
            result.StoreParameters.Namespace       = q.Namespace;
            result.StoreParameters.QueryReturnType = q.ReturnTypeName;
            result.Schema.Name    = q.SchemaName;
            result.Schema.Version = q.SchemaVersion;

            // from
            foreach (var t in q.Query.Tables)
            {
                var schemaTable = qm.Schema.Definitions[t.Value.TableName];
                var ft          = new QueryFromTable(schemaTable);
                ft.Alias = t.Value.ObjectAlias;
                result.FromTables.Add(ft);
            }

            // qc.RegenerateTableLinks();

            // fields
            foreach (var f in q.Query.Fields.Values)
            {
                var table = result.FromTables.FirstOrDefault(t => t.Alias == f.Field.ObjectAlias);

                if (table == null)
                {
                    throw new Exception($"Table with alias '{f.Field.ObjectAlias}' not found");
                }

                var storeProperty = table.Properties.FirstOrDefault(p => p.StoreProperty.Name == f.Field.FieldName);

                if (storeProperty == null)
                {
                    throw new Exception($"Field '{f.Field.FieldName}' not found in table with alias '{f.Field.ObjectAlias}'");
                }

                var newSelectionProperty = new QuerySelectProperty(table, storeProperty.StoreProperty)
                {
                    IsOutput        = f.IsOutput,
                    GroupByFunction = f.GroupByFunction,
                    Alias           = f.FieldAlias != f.Field.FieldName ? f.FieldAlias : ""
                                      // ToDo: Filter is not stored and cannot be loaded
                };

                result.SelectionProperties.Add(newSelectionProperty);
            }

            // Where
            result.WhereClause = QueryExpressionHelper.QueryExprToString(q.Query.Where.Expression);

            return(result);
        }
        public void ReadFromSqlExprTest()
        {
            var res       = new SqlJsonObjectResolver();
            var expEngine = new SqlExpressionEngine(res);
            var expr      = expEngine.BuildExpressionTree("c.CustomerId = 12 AND c.CompanyName = 'ahyu' AND c.EmailAddress = @p1 AND c.ModifiedDate = @p2");
            var result    = QueryExpressionHelper.ReadFromSqlExpr(expr);

            Assert.Equal("ModifiedDate", result.Right.Left.QueryField.Field.FieldName);
            Assert.Equal("=", result.Right.Operator);
            Assert.Equal("@p2", result.Right.Right.Param);
        }
        public void ExpressionParseToStringAndPriorityMappedTest()
        {
            var res       = new SqlJsonObjectResolver();
            var expEngine = new SqlExpressionEngine(res);

            var expr = expEngine.BuildExpressionTree("p.project_id = @p1 AND a.allocation_id = @p2 OR p.project_id = 0");

            var result = QueryExpressionHelper.ReadFromSqlExpr(expr);
            var text   = QueryExpressionHelper.QueryExprToString(result, QueryExpressionHelper.CSharpOperatorsMap);

            Assert.Equal("((p.project_id == @p1) && (a.allocation_id == @p2)) || (p.project_id == 0)", text);
        }
        public void ExpressionParseToStringOrPriorityParensTest()
        {
            var res       = new SqlJsonObjectResolver();
            var expEngine = new SqlExpressionEngine(res);

            var expr = expEngine.BuildExpressionTree("p.project_id = @p1 AND (a.allocation_id = @p2 OR p.project_id = 0)");

            var result = QueryExpressionHelper.ReadFromSqlExpr(expr);
            var text   = QueryExpressionHelper.QueryExprToString(result);

            Assert.Equal("(p.project_id = @p1) AND ((a.allocation_id = @p2) OR (p.project_id = 0))", text);
        }
        public void ExpressionParseToStringTest()
        {
            var res       = new SqlJsonObjectResolver();
            var expEngine = new SqlExpressionEngine(res);

            var expr = expEngine.BuildExpressionTree(
                "((p.project_id = @p1) AND a.allocation_id = @p2) OR ((p.project_id = 0 AND a.allocation_id = 0) OR u.last_name = 'admin')");

            var result = QueryExpressionHelper.ReadFromSqlExpr(expr);
            var text   = QueryExpressionHelper.QueryExprToString(result);

            Assert.Equal("((p.project_id = @p1) AND (a.allocation_id = @p2)) OR (((p.project_id = 0) AND (a.allocation_id = 0)) OR (u.last_name = 'admin'))", text);
        }
        public void GetParamsFromSqlExprTest()
        {
            var res       = new SqlJsonObjectResolver();
            var expEngine = new SqlExpressionEngine(res);
            var expr      = expEngine.BuildExpressionTree("c.CustomerId = 12 AND c.CompanyName = 'ahyu' AND @p1 =   c.EmailAddress AND (c.ModifiedDate = @p2)");
            var dict      = QueryExpressionHelper.GetParamsFromSqlExpr(expr);

            Assert.Equal(2, dict.Values.Count);
            Assert.Contains("@p1", dict.Keys);
            Assert.Contains("@p2", dict.Keys);
            Assert.Equal("c.EmailAddress", dict["@p1"]);
            Assert.Equal("c.ModifiedDate", dict["@p2"]);
        }
Esempio n. 8
0
        protected void GetOrderDetail()
        {
            this.ShowProcess(true);
            // 获取部门ID
            string deptID    = Convert.ToString(OrderEntity.GetObjValue(EntityFieldName.OwnerDepartmentID));
            string companyID = Convert.ToString(OrderEntity.GetObjValue(EntityFieldName.OwnerCompanyID));

            curCompany = DataCore.CompanyList.FirstOrDefault(company => { return(company.ID == companyID); });

            QueryExpression qe = QueryExpressionHelper.Equal(FieldName.OwnerDepartmentID, deptID);

            qe.QueryType = typeof(T_FB_COMPANYBUDGETMODDETAIL).Name;
            fbService.QueryFBEntities(qe);
        }
 private void CheckWhereClause()
 {
     try
     {
         var result = _expressions.BuildExpressionTree(SelectedQuery.WhereClause);
         QueryExpressionHelper.ReadFromSqlExpr(result);
     }
     catch (Exception exc)
     {
         ValidationResults.Add(new RuleValidationResult {
             Type = ValidationResultTypes.Error, Message = $"Where Clause error: {exc.Message}"
         });
         //Errors += "\r\n" + exc.Message;
     }
 }
Esempio n. 10
0
        /// <summary>
        /// 查询数据
        /// </summary>
        private void GetOrderDetail()
        {
            QueryExpression qe = QueryExpressionHelper.Equal(FieldName.OwnerID, DataCore.CurrentUser.Value.ToString());

            qe.QueryType = typeof(T_FB_PERSONMONEYASSIGNMASTER).Name + "FormHR";//Latest

            QueryExpression qeAssign = QueryExpressionHelper.Equal("ASSIGNCOMPANYID", this.OrderEntity.GetObjValue("Entity.ASSIGNCOMPANYID").ToString());

            qeAssign.QueryType         = typeof(T_FB_PERSONMONEYASSIGNMASTER).Name + "FormHR";//Latest
            qeAssign.IsUnCheckRight    = true;
            qeAssign.RelatedExpression = qe;
            qeAssign.IsNoTracking      = false;
            this.ShowProcess(true);
            fbService.QueryFBEntities(qeAssign);
        }
Esempio n. 11
0
        private void GetOrderDetail()
        {
            // 预算月份
            DateTime        dtBudgetDate = (DateTime)this.OrderEntity.GetObjValue("Entity.BUDGETARYMONTH");
            string          dataValue    = dtBudgetDate.ToString("yyyy-MM-dd");
            QueryExpression qeMonth      = QueryExpressionHelper.Equal("BUDGETARYMONTH", dataValue);

            qeMonth.QueryType = typeof(T_FB_DEPTBUDGETAPPLYDETAIL).Name;

            // 预算部门
            QueryExpression qeDept = QueryExpressionHelper.Equal("OWNERDEPARTMENTID", this.OrderEntity.GetObjValue("Entity.OWNERDEPARTMENTID").ToString());

            qeDept.QueryType         = typeof(T_FB_DEPTBUDGETAPPLYDETAIL).Name;
            qeDept.RelatedExpression = qeMonth;

            fbService.QueryFBEntities(qeDept);
        }
Esempio n. 12
0
        private void GetOrderDetail()
        {
            this.ShowProcess(true);
            T_FB_COMPANYBUDGETAPPLYMASTER master = this.OrderEntity.Entity as T_FB_COMPANYBUDGETAPPLYMASTER;

            QueryExpression qeYear = QueryExpressionHelper.Equal("BUDGETYEAR", master.BUDGETYEAR.Add(-1).ToString());

            qeYear.QueryType = typeof(T_FB_COMPANYBUDGETAPPLYDETAIL).Name;

            // 预算部门
            QueryExpression qeDept = QueryExpressionHelper.Equal("OWNERDEPARTMENTID", this.OrderEntity.GetObjValue("Entity.OWNERDEPARTMENTID").ToString());

            qeDept.QueryType         = typeof(T_FB_COMPANYBUDGETAPPLYDETAIL).Name;
            qeDept.RelatedExpression = qeYear;

            fbService.QueryFBEntities(qeDept);
        }
Esempio n. 13
0
        private void GetOrderDetail()
        {
            this.ShowProcess();
            // 预算月份
            DateTime        dtBudgetDate = (DateTime)this.OrderEntity.GetObjValue("Entity.BUDGETARYMONTH");
            string          dataValue    = dtBudgetDate.AddMonths(-1).ToString("yyyy-MM-dd");
            QueryExpression qeMonth      = QueryExpressionHelper.Equal("BUDGETCHECKDATE", dataValue);

            qeMonth.QueryType = typeof(T_FB_DEPTBUDGETADDDETAIL).Name;

            // 预算部门

            QueryExpression qeDept = this.OrderEntity.GetQueryExpression(FieldName.OwnerDepartmentID);

            qeDept.QueryType         = typeof(T_FB_DEPTBUDGETADDDETAIL).Name;
            qeDept.RelatedExpression = qeMonth;

            fbService.QueryFBEntities(qeDept);
        }
Esempio n. 14
0
        public void QueryEntity()
        {
            QueryExpression qeBudget = new QueryExpression();
            QueryExpression qe       = qeBudget;

            qe.PropertyName  = "USABLEMONEY";
            qe.PropertyValue = "0";
            qe.Operation     = QueryExpression.Operations.GreaterThan;
            qe.QueryType     = "QueryBudgetAccount";

            ComboBox       cbbBudgetType = this.expander.FindChildControl <ComboBox>("cbbBudgetType");
            ITextValueItem vitem         = cbbBudgetType.SelectedItem as ITextValueItem;

            if (vitem != null && !string.IsNullOrEmpty(vitem.Value.ToString()))
            {
                QueryExpression qeType = QueryExpressionHelper.Equal("AccountObjectType", vitem.Value.ToString());
                qe.RelatedExpression = qeType;
                qe = qeType;
            }
            LookUp lkObject = this.expander.FindChildControl <LookUp>("lkObject");
            MultiValuesItem <ExtOrgObj> mutilValues = lkObject.SelectItem as MultiValuesItem <ExtOrgObj>;

            if (mutilValues != null)
            {
                Dictionary <OrgTreeItemTypes, string> dictTypes = new Dictionary <OrgTreeItemTypes, string>();
                dictTypes.Add(OrgTreeItemTypes.Company, FieldName.OwnerCompanyID);
                dictTypes.Add(OrgTreeItemTypes.Department, FieldName.OwnerDepartmentID);
                dictTypes.Add(OrgTreeItemTypes.Personnel, FieldName.OwnerID);
                dictTypes.Add(OrgTreeItemTypes.Post, FieldName.OwnerPostID);

                mutilValues.Values.ForEach(item =>
                {
                    string propertyName    = dictTypes[item.ObjectType];
                    QueryExpression qeItem = QueryExpressionHelper.Equal(propertyName, item.ObjectID);
                    qeItem.RelatedType     = QueryExpression.RelationType.Or;
                    qe.RelatedExpression   = qeItem;
                    qe = qeItem;
                });
            }
            fbEntityService.QueryFBEntities(qeBudget);
        }
Esempio n. 15
0
        private void InitData(OrderInfo order)
        {
            OrderEntity oe = new OrderEntity();


            List <ITextValueItem> queryList = new List <ITextValueItem>();

            QueryData qd = new QueryData();

            qd.Text                      = "待我审核的单据";
            qd.Value                     = "AuditedOrder";
            qd.QueryExpression           = QueryExpressionHelper.Equal("AuditedBy", DataCore.CurrentUser.Value.ToString());
            qd.QueryExpression.QueryType = order.Type;
            queryList.Add(qd);

            CommonFunction.FillComboBox(this.cbbQueryList, queryList);

            cbbQueryList.SelectedIndex = 0;

            GetOrders();
        }
Esempio n. 16
0
        private void OnBorrowIDChanged <TEntity>() where TEntity : EntityObject
        {
            DetailGrid dgrid = this.EditForm.FindControl("OrderGrid") as DetailGrid;

            if (dgrid != null)
            {
                dgrid.ShowToolBar = false;
            }

            ObservableCollection <FBEntity> details = this.OrderEntity.GetRelationFBEntities(typeof(TEntity).Name);

            details.Clear();

            T_FB_BORROWAPPLYMASTER borrowMaster = this.OrderEntity.GetObjValue(typeof(T_FB_BORROWAPPLYMASTER).Name.ToEntityString()) as T_FB_BORROWAPPLYMASTER;

            if (borrowMaster == null)
            {
                return;
            }

            QueryExpression qeBorrow    = QueryExpressionHelper.Equal("T_FB_BORROWAPPLYMASTER.BORROWAPPLYMASTERID", borrowMaster.BORROWAPPLYMASTERID);
            QueryExpression qeOwner     = this.OrderEntity.GetQueryExpression(FieldName.OwnerID);
            QueryExpression qeOwnerPost = this.OrderEntity.GetQueryExpression(FieldName.OwnerPostID);

            qeBorrow.QueryType         = typeof(TEntity).Name;
            qeBorrow.RelatedExpression = qeOwner;
            qeOwner.RelatedExpression  = qeOwnerPost;

            FBEntityService service = new FBEntityService();

            service.QueryFBEntitiesCompleted += (o, ea) =>
            {
                ea.Result.ToList().ForEach(item =>
                {
                    details.Add(item);
                    item.FBEntityState = FBEntityState.Added;
                });
            };
            service.QueryFBEntities(qeBorrow);
        }
Esempio n. 17
0
        private void GetOrderDetail()
        {
            T_FB_DEPTTRANSFERMASTER master = this.OrderEntity.Entity as T_FB_DEPTTRANSFERMASTER;

            // 调出单位类型
            QueryExpression qeTransferType = this.OrderEntity.GetQueryExpression("TRANSFERFROMTYPE");

            qeTransferType.PropertyName = "ACCOUNTOBJECTTYPE";
            // 预算单位
            QueryExpression qeFrom = this.OrderEntity.GetQueryExpression("TRANSFERFROM");

            qeFrom.RelatedExpression = qeTransferType;
            if (master.TRANSFERFROMTYPE.Equal(3)) // 个人
            {
                qeFrom.PropertyName = FieldName.OwnerID;

                // 岗位

                QueryExpression qePost = QueryExpressionHelper.Equal(FieldName.OwnerPostID, master.TRANSFERFROMPOSTID);

                qeFrom.RelatedExpression = qePost;
            }
            else
            {
                qeFrom.PropertyName = FieldName.OwnerDepartmentID;
            }

            // 预算年份
            QueryExpression qeYear = QueryExpressionHelper.Equal("BUDGETYEAR", master.BUDGETARYMONTH.Year.ToString());

            qeYear.RelatedExpression = qeFrom;
            // 预算月份
            QueryExpression qeMonth = QueryExpressionHelper.Equal("BUDGETMONTH", master.BUDGETARYMONTH.Month.ToString());

            qeMonth.RelatedExpression = qeYear;
            qeMonth.QueryType         = typeof(T_FB_DEPTTRANSFERDETAIL).Name;
            fbService.QueryFBEntities(qeMonth);
        }
Esempio n. 18
0
        private void OnParameterValueChange()
        {
            OrderEntity orderEntity = this.DataContext as OrderEntity;
            QueryExpression qeTop = null;

            foreach (KeyValuePair<string, string> dict in Parameters)
            {
                object value = orderEntity.GetEntityValue(dict.Value);
                QueryExpression qe = QueryExpressionHelper.Equal(dict.Key, value.ToString());
                qe.RelatedExpression = qeTop;
                qeTop = qe;
            }
            if (qeTop != null)
            {

                qeTop.VisitAction = ((int)this.operationType).ToString();
                qeTop.QueryType = this.OrderDetailGridInfo.OrderDetailEntityInfo.Type;
                qeTop.VisitModuleCode = this.OrderDetailGridInfo.OrderDetailEntityInfo.Type;
                
            }

            SelectedDataManager.QueryExpression = qeTop;
        }
        protected override Expression VisitMethodCall(MethodCallExpression node)
        {
            // Check if the method is SelectMany and get the collection selector
            if (!QueryExpressionHelper.GetSelectManyCollectionSelector(
                    node,
                    out LambdaExpression collectionSelector))
            {
                return(base.VisitMethodCall(node));
            }

            MethodCallExpression defaultIfEmpty =
                ExpressionHelper.SkipConversionNodes(collectionSelector.Body)
                as MethodCallExpression;

            // Check if the collection selector of the SelectMany is DefaultOrEmpty and
            // get its source
            if (!QueryExpressionHelper.GetDefaultOrEmptySource(defaultIfEmpty, out Expression expr))
            {
                return(base.VisitMethodCall(node));
            }

            MethodCallExpression where = expr as MethodCallExpression;

            // Check if the source of DefaultOrEmpty is Where and get its predicate
            if (!QueryExpressionHelper.GetWherePredicate(where, out LambdaExpression predicate))
            {
                return(base.VisitMethodCall(node));
            }

            // Get the result selector of the original SelectMany expression.
            // It is used to achieve the exact same return type as the original SelectMany
            // expression has.

            if (!(ExpressionHelper.SkipQuoteNode(node.Arguments[2]) is LambdaExpression originalResultSelector))
            {
                return(base.VisitMethodCall(node));
            }

            // Check if the source of the Where expression contains any parameter reference
            // The inner selector of the Join statement does not have parameter, so if the
            // source refers the parameter somewhere, it cannot be used as source
            bool parameterReferred = ExpressionSearchVisitor.Search(
                where.Arguments[0],
                collectionSelector.Parameters[0]);

            if (parameterReferred)
            {
                return(base.VisitMethodCall(node));
            }

            // Analyse the predicate, find key mapping
            EqualityMappingDetector detector =
                new EqualityMappingDetector(
                    collectionSelector.Parameters[0],
                    predicate.Parameters[0]);

            if (!detector.Detect(predicate.Body))
            {
                // Cannot convert the predicate into join
                return(base.VisitMethodCall(node));
            }

            // Everything is appropriate for a conversion, visit the inner and outer sources
            Expression outerSource = this.Visit(node.Arguments[0]);
            Expression innerSource = this.Visit(where.Arguments[0]);

            // Inner and outer entity types
            Type outerType = collectionSelector.Parameters[0].Type;
            Type innerType = predicate.Parameters[0].Type;

            LinqJoinKeyHelper.CreateKeySelectors(
                outerType,
                innerType,
                detector.LeftMembers,
                detector.RightMembers,
                out LambdaExpression outerKey,
                out LambdaExpression innerKey);

            // Create the result selector of the GroupJoin
            LambdaExpression groupJoinResultSelector =
                CreateGroupJoinResultSelector(outerType, innerType);

            Type groupJoinResultType = groupJoinResultSelector.Body.Type;

            // Create the GroupJoin method definition
            // Generic arguments:
            // Outer entity type (same as in SelectMany)
            // Inner entity type (same as in SelectMany)
            // Key type
            // Result type (custom tuple)
            MethodInfo groupJoinMethod =
                QueryMethods.GroupJoin.MakeGenericMethod(
                    node.Method.GetGenericArguments()[0],
                    node.Method.GetGenericArguments()[1],
                    outerKey.Body.Type,
                    groupJoinResultType);

            // Create the Join call expression
            // Arguments:
            // Outer collection (visited source of SelectMany expression)
            // Inner collection (visited source of the Where expression)
            // Outer key selector
            // Inner key selector
            // Result selector (tuple)
            Expression groupJoin = Expression.Call(
                groupJoinMethod,
                outerSource,
                innerSource,
                Expression.Quote(outerKey),
                Expression.Quote(innerKey),
                Expression.Quote(groupJoinResultSelector));

            // Collection selector for the post SelectMany expression
            LambdaExpression postSelectManyCollectionSelector =
                CreatePostSelectManyCollectionSelector(
                    innerType,
                    groupJoinResultType);

            // Result selector for the post SelectMany expression.
            LambdaExpression postSelectManyResultSelector =
                CreatePostSelectManyResultSelector(
                    innerType,
                    groupJoinResultType,
                    originalResultSelector);

            // Define the method of the post SelectMany.
            // Generic arguments:
            // Result type of the GroupJoin
            // Inner entity type
            // Result type (same as the original SelectMany)
            MethodInfo postSelectManyMethod =
                QueryMethods.SelectMany.MakeGenericMethod(
                    groupJoinResultType,
                    node.Method.GetGenericArguments()[1],
                    node.Method.GetGenericArguments()[2]);

            Expression postSelectMany =
                Expression.Call(
                    postSelectManyMethod,
                    groupJoin,
                    Expression.Quote(postSelectManyCollectionSelector),
                    Expression.Quote(postSelectManyResultSelector));

            return(postSelectMany);
        }
Esempio n. 20
0
        protected override Expression VisitMethodCall(MethodCallExpression node)
        {
            // Check if the method is SelectMany and get the collection selector
            if (!QueryExpressionHelper.GetSelectManyCollectionSelector(
                    node,
                    out LambdaExpression collectionSelector))
            {
                return(base.VisitMethodCall(node));
            }

            // Unwrap the selector (hopefully Where expression)
            MethodCallExpression where =
                ExpressionHelper.SkipConversionNodes(collectionSelector.Body)
                as MethodCallExpression;


            // Check if the selector of SelectMany is Where and get the predicate
            if (!QueryExpressionHelper.GetWherePredicate(where, out LambdaExpression predicate))
            {
                return(base.VisitMethodCall(node));
            }

            // Check if the source of the Where expression contains any parameter reference
            // The inner selector of the Join statement does not have parameter, so if the
            // source refers the parameter somewhere, it cannot be used as source
            bool parameterReferred = ExpressionSearchVisitor.Search(
                where.Arguments[0],
                collectionSelector.Parameters[0]);

            if (parameterReferred)
            {
                return(base.VisitMethodCall(node));
            }

            // Analyse the predicate, find key mapping
            EqualityMappingDetector detector =
                new EqualityMappingDetector(
                    collectionSelector.Parameters[0],
                    predicate.Parameters[0]);

            if (!detector.Detect(predicate.Body))
            {
                // Cannot convert the predicate into join
                return(base.VisitMethodCall(node));
            }

            // Everything is appropriate for a conversion, visit the inner and outer sources
            Expression outerSource = this.Visit(node.Arguments[0]);
            Expression innerSource = this.Visit(where.Arguments[0]);

            // Inner and outer entity types
            Type outerType = collectionSelector.Parameters[0].Type;
            Type innerType = predicate.Parameters[0].Type;

            LinqJoinKeyHelper.CreateKeySelectors(
                outerType,
                innerType,
                detector.LeftMembers,
                detector.RightMembers,
                out LambdaExpression outerKey,
                out LambdaExpression innerKey);

            // Create the Join method definition:
            // It has the same generic type arguments as the SelectMany
            // Only add the key type (third argument)
            MethodInfo joinMethod = QueryMethods.Join.MakeGenericMethod(
                node.Method.GetGenericArguments()[0],
                node.Method.GetGenericArguments()[1],
                outerKey.Body.Type,
                node.Method.GetGenericArguments()[2]);

            // Create the Join call expression
            // Arguments:
            // Outer collection (visited source of SelectMany expression)
            // Inner collection (visited source of the Where expression)
            // Outer key selector
            // Inner key selector
            // Result selector (same as the SeletMany result selector)
            return(Expression.Call(
                       joinMethod,
                       outerSource,
                       innerSource,
                       Expression.Quote(outerKey),
                       Expression.Quote(innerKey),
                       node.Arguments[2]));
        }
Esempio n. 21
0
        public void QueryEntity()
        {
            QueryExpression qeBudget = new QueryExpression();
            QueryExpression qe       = qeBudget;

            qe.PropertyName  = "USABLEMONEY";
            qe.PropertyValue = "0";
            qe.Operation     = QueryExpression.Operations.GreaterThan;
            qe.QueryType     = "QueryBudgetAccount";
            qe.RightType     = "QueryBudgetAccount";


            // 开始日期
            QueryExpression qeStartYear = new QueryExpression
            {
                PropertyName  = "BUDGETYEAR",
                PropertyValue = DateTime.Now.Year.ToString(),
                Operation     = QueryExpression.Operations.GreaterThanOrEqual
            };

            QueryExpression qeStartMonth = new QueryExpression
            {
                PropertyName  = "BUDGETMONTH",
                PropertyValue = DateTime.Now.Month.ToString(),
                Operation     = QueryExpression.Operations.GreaterThanOrEqual
            };

            qe.RelatedExpression          = qeStartYear;
            qeStartYear.RelatedExpression = qeStartMonth;
            qe = qeStartMonth;

            // 结束日期
            QueryExpression qeEndYear = new QueryExpression
            {
                PropertyName  = "BUDGETYEAR",
                PropertyValue = DateTime.Now.Year.ToString(),
                Operation     = QueryExpression.Operations.LessThanOrEqual
            };

            QueryExpression qeEndMonth = new QueryExpression
            {
                PropertyName  = "BUDGETMONTH",
                PropertyValue = DateTime.Now.Month.ToString(),
                Operation     = QueryExpression.Operations.LessThanOrEqual
            };

            qe.RelatedExpression        = qeEndYear;
            qeEndYear.RelatedExpression = qeEndMonth;
            qe = qeEndMonth;

            // 结束日期
            QueryExpression qeAccountType = new QueryExpression
            {
                PropertyName  = "ACCOUNTOBJECTTYPE",
                PropertyValue = "1",
                Operation     = QueryExpression.Operations.NotEqual
            };

            qe.RelatedExpression        = qeEndMonth;
            qeEndYear.RelatedExpression = qeAccountType;
            qe = qeAccountType;

            QueryExpression qeTemp = null;
            // 选择范围
            MultiValuesItem <ExtOrgObj> mutilValues = lkObject.SelectItem as MultiValuesItem <ExtOrgObj>;

            if (mutilValues != null)
            {
                Dictionary <OrgTreeItemTypes, string> dictTypes = new Dictionary <OrgTreeItemTypes, string>();
                dictTypes.Add(OrgTreeItemTypes.Company, FieldName.OwnerCompanyID);
                dictTypes.Add(OrgTreeItemTypes.Department, FieldName.OwnerDepartmentID);
                dictTypes.Add(OrgTreeItemTypes.Personnel, FieldName.OwnerID);
                dictTypes.Add(OrgTreeItemTypes.Post, FieldName.OwnerPostID);

                mutilValues.Values.ForEach(item =>
                {
                    string propertyName      = dictTypes[item.ObjectType];
                    QueryExpression qeItem   = QueryExpressionHelper.Equal(propertyName, item.ObjectID);
                    qeItem.RelatedType       = QueryExpression.RelationType.Or;
                    qeItem.RelatedExpression = qeTemp;
                    qeTemp = qeItem;
                });
            }

            if (qeTemp != null)
            {
                qe.RelatedExpression = qeTemp;
            }

            fbEntityService.QueryFBEntities(qeBudget);
        }
        public StoreQuery GenerateQuery(IQueryModel qc)
        {
            try
            {
                var result = new StoreQuery()
                {
                    DataService    = qc.StoreParameters.DataService,
                    Name           = qc.StoreParameters.QueryName,
                    Namespace      = qc.StoreParameters.Namespace,
                    ReturnTypeName = qc.StoreParameters.QueryReturnType,
                    SchemaName     = qc.Schema.Name,
                    SchemaFile     = qc.StoreParameters.SchemaFileName,
                    SchemaVersion  = qc.Schema.Version
                };

                result.Query = new StoreQueryDefinition();

                result.Query.Fields = qc.SelectionProperties.ToDictionary(
                    p => p.OutputName,
                    p => new StoreQueryField
                {
                    FieldAlias      = p.OutputName,
                    IsOutput        = p.IsOutput,
                    GroupByFunction = p.GroupByFunction,
                    Field           = new StoreFieldReference {
                        FieldName = p.StoreProperty.Name, ObjectAlias = p.FromTable.Alias
                    }
                });

                result.Query.Tables = qc.FromTables.ToDictionary(
                    t => t.Alias,
                    t => new StoreTableReference {
                    ObjectAlias = t.Alias, TableName = t.StoreDefinition.Name
                }
                    );

                // ToDo: composite foreign keys not supported currently
                List <StoreObjectJoin> joins = qc.FromTableJoins.Where(f => !f.IsDeleted)
                                               .Select(f =>
                {
                    f.Source.JoinType = f.JoinType;
                    return(f.Source);
                }).ToList();

                result.Query.Joins = joins.ToArray();

                var expr      = _expressions.BuildExpressionTree(qc.WhereClause);
                var storeExpr = QueryExpressionHelper.ReadFromSqlExpr(expr);
                result.Query.Where = new StoreQueryCondition {
                    Expression = storeExpr
                };

                var paramsDict = QueryExpressionHelper.GetParamsFromSqlExpr(expr);
                result.Query.Parameters = paramsDict.ToDictionary(d => d.Key, d => new StoreQueryParameter {
                    Name = d.Key, Type = FindStoreProperty(qc, d.Value)?.Type
                });

                return(result);
            }
            catch (Exception exc)
            {
                qc.Errors += "\r\n" + exc.Message;
                return(null);
            }
        }
 public string QueryExprToString(QueryExpression expr, Dictionary <string, string> operatorsMap = null)
 {
     return(QueryExpressionHelper.QueryExprToString(expr, operatorsMap));
 }
Esempio n. 24
0
        private void OnBorrowIDChanged <TEntity>() where TEntity : EntityObject
        {
            DetailGrid dgrid = this.EditForm.FindControl("OrderGrid") as DetailGrid;

            if (dgrid != null)
            {
                dgrid.ShowToolBar = false;
            }

            ObservableCollection <FBEntity> details = this.OrderEntity.GetRelationFBEntities(typeof(TEntity).Name);

            details.Clear();

            T_FB_BORROWAPPLYMASTER borrowMaster = this.OrderEntity.GetObjValue(typeof(T_FB_BORROWAPPLYMASTER).Name.ToEntityString()) as T_FB_BORROWAPPLYMASTER;

            if (borrowMaster == null)
            {
                return;
            }

            int iPayType = 0;

            int.TryParse(this.OrderEntity.GetObjValue("Entity.PAYTYPE").ToString(), out iPayType);
            if (iPayType != 2)
            {
                this.OrderEntity.ReferencedData["Entity.PAYTYPE"] = DataCore.FindRefData("PayTypeData", 2);
            }

            T_FB_CHARGEAPPLYMASTER chargeMaster = this.OrderEntity.Entity as T_FB_CHARGEAPPLYMASTER;

            if (chargeMaster.OWNERID == borrowMaster.OWNERID)
            {
                if (chargeMaster.OWNERPOSTID != borrowMaster.OWNERPOSTID)
                {
                    chargeMaster.OWNERPOSTID   = borrowMaster.OWNERPOSTID;
                    chargeMaster.OWNERPOSTNAME = borrowMaster.OWNERPOSTNAME;
                }

                if (chargeMaster.OWNERDEPARTMENTID != borrowMaster.OWNERDEPARTMENTID)
                {
                    chargeMaster.OWNERDEPARTMENTID   = borrowMaster.OWNERDEPARTMENTID;
                    chargeMaster.OWNERDEPARTMENTNAME = borrowMaster.OWNERDEPARTMENTNAME;
                }

                if (chargeMaster.OWNERCOMPANYID != borrowMaster.OWNERCOMPANYID)
                {
                    chargeMaster.OWNERCOMPANYID   = borrowMaster.OWNERCOMPANYID;
                    chargeMaster.OWNERCOMPANYNAME = borrowMaster.OWNERCOMPANYNAME;
                }
            }

            QueryExpression qeBorrow    = QueryExpressionHelper.Equal("T_FB_BORROWAPPLYMASTER.BORROWAPPLYMASTERID", borrowMaster.BORROWAPPLYMASTERID);
            QueryExpression qeOwner     = this.OrderEntity.GetQueryExpression(FieldName.OwnerID);
            QueryExpression qeOwnerPost = this.OrderEntity.GetQueryExpression(FieldName.OwnerPostID);

            qeBorrow.QueryType         = typeof(TEntity).Name;
            qeBorrow.RelatedExpression = qeOwner;
            qeOwner.RelatedExpression  = qeOwnerPost;

            FBEntityService service = new FBEntityService();

            service.QueryFBEntitiesCompleted += (o, ea) =>
            {
                ea.Result.ToList().ForEach(item =>
                {
                    details.Add(item);
                    item.FBEntityState = FBEntityState.Added;
                });
            };
            service.QueryFBEntities(qeBorrow);
        }
 public async Task <long> CountAsync(Expression <Func <TEntity, bool> > filter = null)
 {
     return(await OnCountAsync(
                filter ?? QueryExpressionHelper.True <TEntity>()));
 }
Esempio n. 26
0
        public void InitBorrowOrder()
        {
            string entity = ReferencedDataInfo.OrderInfo.Type;

            OrderEntity     orderEntity = this.DataContext as OrderEntity;
            QueryExpression qeTop       = null;

            string strEascapeDepIds = "c1dc9c03-31a2-4f0c-be0b-459fdb06b851,4ede37fa-72b5-4939-b087-10bef4520d49,815daaee-b439-4695-874d-ad79ba361add,"
                                      + "0027e9e6-c645-48ec-9333-a2ef507faf57,0abaf119-a470-44ee-8a9e-2e42783b4c86,45995e7d-6062-49e6-b08f-1da59729f9f1";

            string strCurDepId = string.Empty;

            foreach (KeyValuePair <string, string> dict in Parameters)
            {
                object objvalue = orderEntity.GetEntityValue(dict.Value);
                if (dict.Key == "OWNERDEPARTMENTID" && objvalue != null)
                {
                    strCurDepId = objvalue.ToString();
                    continue;
                }

                if (dict.Key == "OWNERPOSTID")
                {
                    if (strEascapeDepIds.Contains(strCurDepId))
                    {
                        continue;
                    }
                }
                QueryExpression qe = QueryExpressionHelper.Equal(dict.Key, objvalue.ToString());
                qe.RelatedExpression = qeTop;
                qeTop = qe;
            }

            // 未偿还
            QueryExpression qeIsRepaied = QueryExpressionHelper.Equal("ISREPAIED", "1");

            qeIsRepaied.Operation         = QueryExpression.Operations.NotEqual;
            qeIsRepaied.RelatedExpression = qeTop;
            qeTop = qeIsRepaied;

            if (qeTop != null)
            {
                qeTop.VisitAction     = ((int)this.OperationType).ToString();
                qeTop.QueryType       = entity;
                qeTop.VisitModuleCode = entity;
                qeTop.Include         = new System.Collections.ObjectModel.ObservableCollection <string>();
                qeTop.Include.Add("T_FB_EXTENSIONALORDER.T_FB_EXTENSIONALTYPE");
                qeTop.Include.Add("T_FB_BORROWAPPLYDETAIL.T_FB_SUBJECT");
            }

            SelectedDataManager.QueryExpression = qeTop;
            SelectedForm sf = new SelectedForm();

            sf.TitleContent        = "借款单";
            sf.SelectedDataManager = this.SelectedDataManager;
            sf.ReferenceDataType   = this.ReferencedDataInfo.Type;
            sf.SelectionMode       = DataGridSelectionMode.Single;
            sf.SelectedCompleted  += (o, e) =>
            {
                FBEntity       fbEntity = sf.SelectedItems.FirstOrDefault();
                Type           type     = CommonFunction.GetType(this.ReferencedDataInfo.Type, CommonFunction.TypeCategory.ReferencedData);
                ITextValueItem item     = Activator.CreateInstance(type) as ITextValueItem;
                item.Value      = fbEntity.Entity;
                this.SelectItem = item;
            };
            sf.Show();
        }
        private static IQueryModel ReadQueryTables(List <IQueryModel> loadedSubQueryList, string name, StoreSchema schema, StoreQueryDefinition queryDef, Dictionary <string, StoreQueryDefinition> subQueries)
        {
            var result = loadedSubQueryList.FirstOrDefault(l => l.Name == name);

            if (result != null)
            {
                return(result);
            }

            queryDef = queryDef ?? subQueries[name];
            result   = new QueryModel()
            {
                Name = name
            };

            foreach (var t in queryDef.Tables)
            {
                if (schema.Definitions.ContainsKey(t.Value.TableName))
                {
                    // not subquery table
                    var schemaTable = schema.Definitions[t.Value.TableName];
                    var ft          = new QueryFromTable(schemaTable);
                    ft.Alias = t.Value.ObjectAlias;
                    result.FromTables.Add(ft);
                }
                else
                {
                    if (!subQueries.ContainsKey(t.Value.TableName))
                    {
                        throw new Exception($"Table or SubQuery with name '{t.Value.TableName}' not found");
                    }

                    var subQuery = ReadQueryTables(loadedSubQueryList, t.Value.TableName, schema, null, subQueries);
                    var ft       = new QueryFromTable(subQuery);
                    ft.Alias = t.Value.ObjectAlias;
                    result.FromTables.Add(ft);
                }
            }

            loadedSubQueryList.Add(result);

            // fields
            foreach (var f in queryDef.Fields.Values)
            {
                var table = result.FromTables.FirstOrDefault(t => t.Alias == f.Field.ObjectAlias);

                if (table == null)
                {
                    throw new Exception($"Table with alias '{f.Field.ObjectAlias}' not found");
                }

                var storeProperty = table.Properties.FirstOrDefault(p => p.Name == f.Field.FieldName);

                if (storeProperty == null)
                {
                    throw new Exception($"Field '{f.Field.FieldName}' not found in table with alias '{f.Field.ObjectAlias}'");
                }

                var newSelectionProperty = new QuerySelectProperty(table, storeProperty.OriginalStoreProperty)
                {
                    IsOutput        = f.IsOutput,
                    GroupByFunction = f.GroupByFunction,
                    Having          = f.GroupByFilter,
                    Alias           = f.FieldAlias != f.Field.FieldName ? f.FieldAlias : ""
                                      // ToDo: Filter is not stored and cannot be loaded
                };

                result.SelectionProperties.Add(newSelectionProperty);
            }

            // Joins
            foreach (var j in queryDef.Joins)
            {
            }

            result.FromTableJoins = queryDef.Joins.Select(j => new TableJoinModel()
            {
                IsDeleted = false,
                JoinType  = j.JoinType,
                Source    = j
            }).ToList();

            // Where
            result.WhereClause = QueryExpressionHelper.QueryExprToString(queryDef.Where.Expression);

            return(result);
        }