private void BuildAssociationCondition(ExpressionBuilder builder, TableContext parent, AssociationDescriptor association, SqlSearchCondition condition)
            {
                for (var i = 0; i < association.ThisKey.Length; i++)
                {
                    if (!parent.SqlTable.Fields.TryGetValue(association.ThisKey[i], out var field1))
                    {
                        throw new LinqException("Association key '{0}' not found for type '{1}.", association.ThisKey[i], parent.ObjectType);
                    }

                    if (!SqlTable.Fields.TryGetValue(association.OtherKey[i], out var field2))
                    {
                        throw new LinqException("Association key '{0}' not found for type '{1}.", association.OtherKey[i], ObjectType);
                    }

                    ISqlPredicate predicate = new SqlPredicate.ExprExpr(
                        field1, SqlPredicate.Operator.Equal, field2);

                    predicate = builder.Convert(parent, predicate);

                    condition.Conditions.Add(new SqlCondition(false, predicate));
                }

                if (ObjectType != OriginalType)
                {
                    var predicate = Builder.MakeIsPredicate(this, OriginalType);

                    if (predicate.GetType() != typeof(SqlPredicate.Expr))
                    {
                        condition.Conditions.Add(new SqlCondition(false, predicate));
                    }
                }

                RegularConditionCount = condition.Conditions.Count;
                ExpressionPredicate   = Association.GetPredicate(parent.ObjectType, ObjectType);

                if (ExpressionPredicate != null)
                {
                    ExpressionPredicate = (LambdaExpression)Builder.ConvertExpressionTree(ExpressionPredicate);

                    var expr = Builder.ConvertExpression(ExpressionPredicate.Body.Unwrap());

                    Builder.BuildSearchCondition(
                        new ExpressionContext(parent.Parent, new IBuildContext[] { parent, this }, ExpressionPredicate),
                        expr,
                        condition.Conditions,
                        false);
                }
            }
        internal static Expression <Func <TParent, TChild, bool> > BuildJoinExpression <TParent, TChild>(
            AssociationDescriptor assoc, Type declaringType, Type memberEntityType)
        {
            var predicate = assoc.GetPredicate(declaringType, memberEntityType);

            var parentParam = predicate?.Parameters.FirstOrDefault() ?? Expression.Parameter(declaringType, "p");

            var childParam = predicate?.Parameters.Skip(1).FirstOrDefault() ??
                             Expression.Parameter(memberEntityType, "c");

            var previousExpr = BuildJoinClauseByForeignKey(assoc, predicate, parentParam, childParam);

            if (previousExpr is LambdaExpression lambda)
            {
                previousExpr = lambda.Body;
            }

            var expr = Expression.Lambda <Func <TParent, TChild, bool> >(previousExpr, parentParam, childParam);

            return(expr);
        }
Beispiel #3
0
        // Returns
        // (ParentType p) => dc.GetTable<ObjectType>().Where(...)
        // (ParentType p) => dc.GetTable<ObjectType>().Where(...).DefaultIfEmpty
        public static LambdaExpression CreateAssociationQueryLambda(ExpressionBuilder builder, AccessorMember onMember, AssociationDescriptor association,
                                                                    Type parentOriginalType,
                                                                    Type parentType,
                                                                    Type objectType, bool inline, bool enforceDefault,
                                                                    List <LoadWithInfo[]>?loadWith, out bool isLeft)
        {
            var dataContextConstant = Expression.Constant(builder.DataContext, builder.DataContext.GetType());

            // We are trying to keep fast cache hit behaviour, so cache check should be added only if needed
            //
            bool shouldAddCacheCheck = false;

            bool cacheCheckAdded = false;

            LambdaExpression?definedQueryMethod = null;

            if (association.HasQueryMethod())
            {
                // here we tell for Expression Comparer to compare optimized Association expressions
                //
                definedQueryMethod = (LambdaExpression)builder.AddQueryableMemberAccessors(onMember, builder.DataContext, (mi, dc) =>
                {
                    var queryLambda         = association.GetQueryMethod(parentType, objectType) ?? throw new InvalidOperationException();
                    var optimizationContext = new ExpressionTreeOptimizationContext(dc);
                    var optimizedExpr       = optimizationContext.ExposeExpression(queryLambda);
                    optimizedExpr           = optimizationContext.ExpandQueryableMethods(optimizedExpr);
                    optimizedExpr           = optimizedExpr.OptimizeExpression() !;
                    return(optimizedExpr);
                });

                cacheCheckAdded = true;

                var parameterMatch = new Dictionary <ParameterExpression, Expression>();
                if (onMember.Arguments == null)
                {
                    if (definedQueryMethod.Parameters.Count > 1 && typeof(IDataContext).IsSameOrParentOf(definedQueryMethod.Parameters[1].Type))
                    {
                        parameterMatch.Add(definedQueryMethod.Parameters[1], dataContextConstant);
                    }
                }
                else
                {
                    var definedCount   = definedQueryMethod.Parameters.Count;
                    var argumentsCount = onMember.Arguments.Count;
                    var diff           = definedCount - argumentsCount;
                    for (int i = definedCount - 1; i >= diff; i--)
                    {
                        parameterMatch.Add(definedQueryMethod.Parameters[i], onMember.Arguments[i - diff]);
                    }
                }

                var body = definedQueryMethod.Body.Transform(e =>
                {
                    if (e.NodeType == ExpressionType.Parameter &&
                        parameterMatch.TryGetValue((ParameterExpression)e, out var newExpression))
                    {
                        return(newExpression);
                    }

                    return(e);
                });

                definedQueryMethod = Expression.Lambda(body, definedQueryMethod.Parameters[0]);
            }

            var shouldAddDefaultIfEmpty = enforceDefault;

            if (definedQueryMethod == null)
            {
                var parentParam = Expression.Parameter(parentType, "parent");
                var childParam  = Expression.Parameter(objectType, association.AliasName);

                var parentAccessor = TypeAccessor.GetAccessor(parentType);
                var childAccessor  = TypeAccessor.GetAccessor(objectType);

                Expression?predicate = null;
                for (var i = 0; i < association.ThisKey.Length; i++)
                {
                    var parentName   = association.ThisKey[i];
                    var parentMember = parentAccessor.Members.Find(m => m.MemberInfo.Name == parentName);

                    if (parentMember == null)
                    {
                        throw new LinqException("Association key '{0}' not found for type '{1}.", parentName,
                                                parentType);
                    }

                    var childName   = association.OtherKey[i];
                    var childMember = childAccessor.Members.Find(m => m.MemberInfo.Name == childName);

                    if (childMember == null)
                    {
                        throw new LinqException("Association key '{0}' not found for type '{1}.", childName,
                                                objectType);
                    }

                    var current = ExpressionBuilder.Equal(builder.MappingSchema,
                                                          Expression.MakeMemberAccess(parentParam, parentMember.MemberInfo),
                                                          Expression.MakeMemberAccess(childParam, childMember.MemberInfo));

                    predicate = predicate == null ? current : Expression.AndAlso(predicate, current);
                }

                var expressionPredicate = association.GetPredicate(parentType, objectType);

                if (expressionPredicate != null)
                {
                    shouldAddDefaultIfEmpty = true;
                    shouldAddCacheCheck     = true;

                    var replacedBody = expressionPredicate.GetBody(parentParam, childParam);

                    predicate = predicate == null ? replacedBody : Expression.AndAlso(predicate, replacedBody);
                }

                if (predicate == null)
                {
                    throw new LinqException("Can not generate Association predicate");
                }

                if (inline && !shouldAddDefaultIfEmpty)
                {
                    var ed = builder.MappingSchema.GetEntityDescriptor(objectType);
                    if (ed.QueryFilterFunc != null)
                    {
                        shouldAddDefaultIfEmpty = true;
                        shouldAddCacheCheck     = true;
                    }
                }

                var queryParam = Expression.Call(Methods.LinqToDB.GetTable.MakeGenericMethod(objectType), dataContextConstant);

                var        filterLambda = Expression.Lambda(predicate, childParam);
                Expression body         = Expression.Call(Methods.Queryable.Where.MakeGenericMethod(objectType), queryParam,
                                                          filterLambda);

                definedQueryMethod = Expression.Lambda(body, parentParam);
            }
            else
            {
                shouldAddDefaultIfEmpty = true;
                var bodyExpression = definedQueryMethod.Body.Unwrap();
                if (bodyExpression.NodeType == ExpressionType.Call)
                {
                    var mc = (MethodCallExpression)bodyExpression;
                    if (mc.IsSameGenericMethod(Methods.Queryable.DefaultIfEmpty, Methods.Queryable.DefaultIfEmptyValue))
                    {
                        shouldAddDefaultIfEmpty = false;
                    }
                }
            }

            if (!cacheCheckAdded && shouldAddCacheCheck)
            {
                // here we tell for Expression Comparer to compare optimized Association expressions
                //
                var closureExpr = definedQueryMethod;
                definedQueryMethod = (LambdaExpression)builder.AddQueryableMemberAccessors(onMember, builder.DataContext, (mi, dc) =>
                {
                    var optimizationContext = new ExpressionTreeOptimizationContext(dc);
                    var optimizedExpr       = optimizationContext.ExposeExpression(closureExpr);
                    optimizedExpr           = optimizationContext.ExpandQueryableMethods(optimizedExpr);
                    optimizedExpr           = optimizedExpr.OptimizeExpression() !;
                    return(optimizedExpr);
                });
            }

            if (loadWith != null)
            {
                var associationLoadWith = GetLoadWith(loadWith)?
                                          .FirstOrDefault(li => li.Info.MemberInfo == association.MemberInfo);

                if (associationLoadWith != null &&
                    (associationLoadWith.Info.MemberFilter != null || associationLoadWith.Info.FilterFunc != null))
                {
                    var body = definedQueryMethod.Body.Unwrap();

                    var memberFilter = associationLoadWith.Info.MemberFilter;
                    if (memberFilter != null)
                    {
                        var elementType = EagerLoading.GetEnumerableElementType(memberFilter.Parameters[0].Type,
                                                                                builder.MappingSchema);
                        var filtered   = Expression.Convert(body, typeof(IEnumerable <>).MakeGenericType(elementType));
                        var filterBody = memberFilter.GetBody(filtered);
                        body = Expression.Call(
                            Methods.Enumerable.AsQueryable.MakeGenericMethod(objectType), filterBody);
                    }

                    var loadWithFunc = associationLoadWith.Info.FilterFunc;

                    if (loadWithFunc != null)
                    {
                        loadWithFunc = loadWithFunc.Unwrap();
                        if (loadWithFunc is LambdaExpression lambda)
                        {
                            body = lambda.GetBody(body);
                        }
                        else
                        {
                            var filterDelegate = loadWithFunc.EvaluateExpression <Delegate>() ??
                                                 throw new LinqException("Cannot convert filter function '{loadWithFunc}' to Delegate.");

                            var arumentType = filterDelegate.GetType().GetGenericArguments()[0].GetGenericArguments()[0];
                            // check for fake argument q => q
                            if (arumentType.IsSameOrParentOf(objectType))
                            {
                                var query    = ExpressionQueryImpl.CreateQuery(objectType, builder.DataContext, body);
                                var filtered = (IQueryable)filterDelegate.DynamicInvoke(query) !;
                                body = filtered.Expression;
                            }
                        }
                    }

                    definedQueryMethod = Expression.Lambda(body, definedQueryMethod.Parameters);
                }

                if (associationLoadWith?.NextLoadWith != null && associationLoadWith.NextLoadWith.Count > 0)
                {
                    definedQueryMethod = (LambdaExpression)EnrichTablesWithLoadWith(builder.DataContext, definedQueryMethod, objectType,
                                                                                    associationLoadWith.NextLoadWith, builder.MappingSchema);
                }
            }

            if (parentOriginalType != parentType)
            {
                // add discriminator filter
                var ed = builder.MappingSchema.GetEntityDescriptor(parentOriginalType);
                foreach (var inheritanceMapping in ed.InheritanceMapping)
                {
                    if (inheritanceMapping.Type == parentType)
                    {
                        var objParam     = Expression.Parameter(objectType, "o");
                        var filterLambda = Expression.Lambda(ExpressionBuilder.Equal(builder.MappingSchema,
                                                                                     Expression.MakeMemberAccess(definedQueryMethod.Parameters[0], inheritanceMapping.Discriminator.MemberInfo),
                                                                                     Expression.Constant(inheritanceMapping.Code)), objParam);

                        var body = definedQueryMethod.Body.Unwrap();
                        body = Expression.Call(Methods.Queryable.Where.MakeGenericMethod(objectType),
                                               body, filterLambda);
                        definedQueryMethod = Expression.Lambda(body, definedQueryMethod.Parameters);

                        shouldAddDefaultIfEmpty = true;
                        break;
                    }
                }
            }

            if (inline && shouldAddDefaultIfEmpty)
            {
                var body = definedQueryMethod.Body.Unwrap();
                body = Expression.Call(Methods.Queryable.DefaultIfEmpty.MakeGenericMethod(objectType), body);
                definedQueryMethod = Expression.Lambda(body, definedQueryMethod.Parameters);
                isLeft             = true;
            }
            else
            {
                isLeft = false;
            }

            definedQueryMethod = (LambdaExpression)builder.ConvertExpressionTree(definedQueryMethod);
            definedQueryMethod = (LambdaExpression)builder.ConvertExpression(definedQueryMethod);
            definedQueryMethod = (LambdaExpression)definedQueryMethod.OptimizeExpression() !;

            return(definedQueryMethod);
        }
            public AssociatedTableContext(
                [JetBrains.Annotations.NotNull] ExpressionBuilder builder,
                [JetBrains.Annotations.NotNull] TableContext parent,
                [JetBrains.Annotations.NotNull] AssociationDescriptor association
                )
                : base(builder, parent.SelectQuery)
            {
                if (builder == null)
                {
                    throw new ArgumentNullException(nameof(builder));
                }
                if (parent == null)
                {
                    throw new ArgumentNullException(nameof(parent));
                }
                if (association == null)
                {
                    throw new ArgumentNullException(nameof(association));
                }

                var type = association.MemberInfo.GetMemberType();
                var left = association.CanBeNull;

                if (typeof(IEnumerable).IsSameOrParentOf(type))
                {
                    var eTypes = type.GetGenericArguments(typeof(IEnumerable <>));
                    type   = eTypes != null && eTypes.Length > 0 ? eTypes[0] : type.GetListItemType();
                    IsList = true;
                }

                OriginalType       = type;
                ObjectType         = GetObjectType();
                EntityDescriptor   = Builder.MappingSchema.GetEntityDescriptor(ObjectType);
                InheritanceMapping = EntityDescriptor.InheritanceMapping;
                SqlTable           = new SqlTable(builder.MappingSchema, ObjectType);

                Association       = association;
                ParentAssociation = parent;

                SqlJoinedTable join;

                var queryMethod = Association.GetQueryMethod(parent.ObjectType, ObjectType);

                if (queryMethod != null)
                {
                    var dcParam     = queryMethod.Parameters[1];
                    var resultParam = Expression.Parameter(ObjectType);

                    Expression dcConst = Expression.Constant(builder.DataContext);
                    if (dcParam.Type != typeof(IDataContext))
                    {
                        dcConst = Expression.Convert(dcConst, dcParam.Type);
                    }

                    var body = queryMethod.Body.Transform(e => e == dcParam ? dcConst : e);
                    body        = Expression.Convert(body, typeof(IEnumerable <>).MakeGenericType(ObjectType));
                    queryMethod = Expression.Lambda(body, queryMethod.Parameters[0]);

                    var selectManyMethodInfo = _selectManyMethodInfo.MakeGenericMethod(parent.ObjectType, ObjectType, ObjectType);
                    var resultLamba          = Expression.Lambda(resultParam, Expression.Parameter(parent.ObjectType), resultParam);
                    var selectManyMethod     = Expression.Call(null, selectManyMethodInfo, parent.Expression, queryMethod, resultLamba);
                    var ownerTableSource     = SelectQuery.From.Tables[0];

                    _innerContext = builder.BuildSequence(new BuildInfo(this, selectManyMethod, new SelectQuery())
                    {
                        IsAssociationBuilt = true
                    });

                    var associationQuery = _innerContext.SelectQuery;

                    if (associationQuery.Select.From.Tables.Count < 1)
                    {
                        throw new LinqToDBException("Invalid association query. It is not possible to inline query.");
                    }

                    var foundIndex = associationQuery.Select.From.Tables.FindIndex(t =>
                                                                                   t.Source is SqlTable sqlTable && QueryHelper.IsEqualTables(sqlTable, parent.SqlTable));

                    if (foundIndex < 0)
                    {
                        throw new LinqToDBException("Invalid association query. It is not possible to inline query. Can not find owner table.");
                    }

                    var sourceToReplace = associationQuery.Select.From.Tables[foundIndex];

                    if (left)
                    {
                        foreach (var joinedTable in sourceToReplace.Joins)
                        {
                            if (joinedTable.JoinType == JoinType.Inner)
                            {
                                joinedTable.JoinType = JoinType.Left;
                            }
                            else if (joinedTable.JoinType == JoinType.CrossApply)
                            {
                                joinedTable.JoinType = JoinType.OuterApply;
                            }

                            joinedTable.IsWeak = true;
                        }
                    }

                    ownerTableSource.Joins.AddRange(sourceToReplace.Joins);

                    // prepare fields mapping to replace fields that will be generated by association query
                    _replaceMap =
                        ((SqlTable)sourceToReplace.Source).Fields.Values.ToDictionary(f => (ISqlExpression)f,
                                                                                      f => parent.SqlTable.Fields[f.Name]);

                    ownerTableSource.Walk(false, e =>
                    {
                        if (_replaceMap.TryGetValue(e, out var newField))
                        {
                            return(newField);
                        }
                        return(e);
                    });

                    ParentAssociationJoin = sourceToReplace.Joins.FirstOrDefault();
                    join = ParentAssociationJoin;

                    // add rest of tables
                    SelectQuery.From.Tables.AddRange(associationQuery.Select.From.Tables.Where(t => t != sourceToReplace));
                }
                else
                {
                    var psrc = parent.SelectQuery.From[parent.SqlTable];
                    join = left ? SqlTable.WeakLeftJoin().JoinedTable : SqlTable.WeakInnerJoin().JoinedTable;

                    ParentAssociationJoin = join;

                    psrc.Joins.Add(join);

                    for (var i = 0; i < association.ThisKey.Length; i++)
                    {
                        if (!parent.SqlTable.Fields.TryGetValue(association.ThisKey[i], out var field1))
                        {
                            throw new LinqException("Association key '{0}' not found for type '{1}.", association.ThisKey[i], parent.ObjectType);
                        }

                        if (!SqlTable.Fields.TryGetValue(association.OtherKey[i], out var field2))
                        {
                            throw new LinqException("Association key '{0}' not found for type '{1}.", association.OtherKey[i], ObjectType);
                        }

                        //					join.Field(field1).Equal.Field(field2);

                        ISqlPredicate predicate = new SqlPredicate.ExprExpr(
                            field1, SqlPredicate.Operator.Equal, field2);

                        predicate = builder.Convert(parent, predicate);

                        join.Condition.Conditions.Add(new SqlCondition(false, predicate));
                    }

                    if (ObjectType != OriginalType)
                    {
                        var predicate = Builder.MakeIsPredicate(this, OriginalType);

                        if (predicate.GetType() != typeof(SqlPredicate.Expr))
                        {
                            join.Condition.Conditions.Add(new SqlCondition(false, predicate));
                        }
                    }

                    RegularConditionCount = join.Condition.Conditions.Count;
                    ExpressionPredicate   = Association.GetPredicate(parent.ObjectType, ObjectType);

                    if (ExpressionPredicate != null)
                    {
                        ExpressionPredicate = (LambdaExpression)Builder.ConvertExpressionTree(ExpressionPredicate);

                        var expr = Builder.ConvertExpression(ExpressionPredicate.Body.Unwrap());

                        Builder.BuildSearchCondition(
                            new ExpressionContext(parent.Parent, new IBuildContext[] { parent, this }, ExpressionPredicate),
                            expr,
                            join.Condition.Conditions,
                            false);
                    }
                }

                if (!association.AliasName.IsNullOrEmpty() && join != null)
                {
                    join.Table.Alias = association.AliasName;
                }
                else
                {
                    if (!Common.Configuration.Sql.AssociationAlias.IsNullOrEmpty() && join != null)
                    {
                        join.Table.Alias = string.Format(Common.Configuration.Sql.AssociationAlias,
                                                         association.MemberInfo.Name);
                    }
                }

                Init(false);
            }
            public AssociatedTableContext(
                [JetBrains.Annotations.NotNull] ExpressionBuilder builder,
                [JetBrains.Annotations.NotNull] TableContext parent,
                [JetBrains.Annotations.NotNull] AssociationDescriptor association
                )
                : base(builder, parent.SelectQuery)
            {
                if (builder == null)
                {
                    throw new ArgumentNullException(nameof(builder));
                }
                if (parent == null)
                {
                    throw new ArgumentNullException(nameof(parent));
                }
                if (association == null)
                {
                    throw new ArgumentNullException(nameof(association));
                }

                var type = association.MemberInfo.GetMemberType();
                var left = association.CanBeNull;

                if (typeof(IEnumerable).IsSameOrParentOf(type))
                {
                    var eTypes = type.GetGenericArguments(typeof(IEnumerable <>));
                    type   = eTypes != null && eTypes.Length > 0 ? eTypes[0] : type.GetListItemType();
                    IsList = true;
                }

                OriginalType       = type;
                ObjectType         = GetObjectType();
                EntityDescriptor   = Builder.MappingSchema.GetEntityDescriptor(ObjectType);
                InheritanceMapping = EntityDescriptor.InheritanceMapping;
                SqlTable           = new SqlTable(builder.MappingSchema, ObjectType);

                var psrc = parent.SelectQuery.From[parent.SqlTable];
                var join = left ? SqlTable.WeakLeftJoin() : SqlTable.WeakInnerJoin();

                if (!association.AliasName.IsNullOrEmpty())
                {
                    join.JoinedTable.Table.Alias = association.AliasName;
                }
                else
                {
                    if (!Common.Configuration.Sql.AssociationAlias.IsNullOrEmpty())
                    {
                        join.JoinedTable.Table.Alias = string.Format(Common.Configuration.Sql.AssociationAlias,
                                                                     association.MemberInfo.Name);
                    }
                }

                Association           = association;
                ParentAssociation     = parent;
                ParentAssociationJoin = join.JoinedTable;

                psrc.Joins.Add(join.JoinedTable);

                for (var i = 0; i < association.ThisKey.Length; i++)
                {
                    if (!parent.SqlTable.Fields.TryGetValue(association.ThisKey[i], out var field1))
                    {
                        throw new LinqException("Association key '{0}' not found for type '{1}.", association.ThisKey[i], parent.ObjectType);
                    }

                    if (!SqlTable.Fields.TryGetValue(association.OtherKey[i], out var field2))
                    {
                        throw new LinqException("Association key '{0}' not found for type '{1}.", association.OtherKey[i], ObjectType);
                    }

//					join.Field(field1).Equal.Field(field2);

                    ISqlPredicate predicate = new SqlPredicate.ExprExpr(
                        field1, SqlPredicate.Operator.Equal, field2);

                    predicate = builder.Convert(parent, predicate);

                    join.JoinedTable.Condition.Conditions.Add(new SqlCondition(false, predicate));
                }

                if (ObjectType != OriginalType)
                {
                    var predicate = Builder.MakeIsPredicate(this, OriginalType);

                    if (predicate.GetType() != typeof(SqlPredicate.Expr))
                    {
                        join.JoinedTable.Condition.Conditions.Add(new SqlCondition(false, predicate));
                    }
                }

                RegularConditionCount = join.JoinedTable.Condition.Conditions.Count;
                ExpressionPredicate   = Association.GetPredicate(parent.ObjectType, ObjectType);

                if (ExpressionPredicate != null)
                {
                    ExpressionPredicate = (LambdaExpression)Builder.ConvertExpressionTree(ExpressionPredicate);

                    var expr = Builder.ConvertExpression(ExpressionPredicate.Body.Unwrap());

                    Builder.BuildSearchCondition(
                        new ExpressionContext(parent.Parent, new IBuildContext[] { parent, this }, ExpressionPredicate),
                        expr,
                        join.JoinedTable.Condition.Conditions,
                        false);
                }

                Init(false);
            }