public override DbExpression Visit(DbNewInstanceExpression expression)
            {
                var arguments = expression.Arguments.Select(a =>
                {
                    var propertyArg = a as DbPropertyExpression;
                    if (propertyArg != null && _typesToTrim.Contains(propertyArg.Property.TypeUsage.EdmType.Name))
                    {
                        return(EdmFunctions.Trim(a));
                    }

                    return(a);
                });

                var temp = new List <DbExpression>();

                foreach (var a in expression.Arguments)
                {
                    var propertyArg = a as DbPropertyExpression;
                    if (propertyArg != null && _typesToTrim.Contains(propertyArg.Property.TypeUsage.EdmType.Name))
                    {
                        temp.Add(EdmFunctions.Trim(a));
                    }
                    else
                    {
                        temp.Add(a);
                    }
                }

                return(DbExpressionBuilder.New(expression.ResultType, temp));
            }
        public override Expression Visit(DbNewInstanceExpression expression)
        {
            Type resultType = edmTypeConverter.Convert(expression.ResultType);

            Expression[] args = this.VisitExpressions(expression.Arguments);
            return this.CreateSelector(args, resultType);
        }
Exemple #3
0
 public override DbExpression Visit(DbNewInstanceExpression expression)
 {
     return((DbExpression)DbExpressionBuilder.NewRow((IEnumerable <KeyValuePair <string, DbExpression> >)expression.Arguments.Cast <DbPropertyExpression>().Select(propertyExpression => new
     {
         propertyExpression = propertyExpression,
         resultBinding = this._currentFunctionMapping.ResultBindings.Single <ModificationFunctionResultBinding>((Func <ModificationFunctionResultBinding, bool>)(rb => this._entityContainerMapping.EntitySetMappings.SelectMany((Func <EntitySetMapping, IEnumerable <EntityTypeMapping> >)(esm => (IEnumerable <EntityTypeMapping>)esm.EntityTypeMappings), (esm, etm) => new
         {
             esm = esm,
             etm = etm
         }).SelectMany(_param0 => (IEnumerable <MappingFragment>)_param0.etm.MappingFragments, (_param0, mf) => new
         {
             \u003C\u003Eh__TransparentIdentifier7 = _param0,
             mf = mf
         }).SelectMany(_param0 => _param0.mf.PropertyMappings.OfType <ScalarPropertyMapping>(), (_param0, pm) => new
         {
             \u003C\u003Eh__TransparentIdentifier8 = _param0,
             pm = pm
         }).Where(_param1 =>
         {
             if (_param1.pm.Column.EdmEquals((MetadataItem)propertyExpression.Property))
             {
                 return _param1.pm.Column.DeclaringType.EdmEquals((MetadataItem)propertyExpression.Property.DeclaringType);
             }
             return false;
         }).Select(_param0 => _param0.pm.Property).Contains <EdmProperty>(rb.Property)))
     }).Select(_param0 => new KeyValuePair <string, DbExpression>(_param0.resultBinding.ColumnName, (DbExpression)_param0.propertyExpression)).ToList <KeyValuePair <string, DbExpression> >()));
 }
Exemple #4
0
        protected void VisitNewInstanceExpression(SelectStatement select,
                                                  DbNewInstanceExpression expression)
        {
            Debug.Assert(expression.ResultType.EdmType is RowType);

            RowType row = expression.ResultType.EdmType as RowType;

            for (int i = 0; i < expression.Arguments.Count; i++)
            {
                ColumnFragment col;

                SqlFragment fragment = expression.Arguments[i].Accept(this);
                if (fragment is ColumnFragment)
                {
                    col = fragment as ColumnFragment;
                }
                else
                {
                    col         = new ColumnFragment(null, null);
                    col.Literal = fragment;
                }

                col.ColumnAlias = row.Properties[i].Name;
                select.Columns.Add(col);
            }
        }
Exemple #5
0
 public override void Visit(DbNewInstanceExpression e)
 {
     VisitExprKind(e.ExpressionKind);
     _key.Append(':');
     _key.Append(e.ResultType.EdmType.Identity);
     _key.Append('(');
     foreach (var a in e.Arguments)
     {
         _key.Append('(');
         a.Accept(this);
         _key.Append(')');
     }
     if (e.HasRelatedEntityReferences)
     {
         foreach (DbRelatedEntityRef relatedRef in e.RelatedEntityReferences)
         {
             _key.Append("RE(A(");
             _key.Append(relatedRef.SourceEnd.DeclaringType.Identity);
             _key.Append(")(");
             _key.Append(relatedRef.SourceEnd.Name);
             _key.Append("->");
             _key.Append(relatedRef.TargetEnd.Name);
             _key.Append(")(");
             relatedRef.TargetEntityReference.Accept(this);
             _key.Append("))");
         }
     }
     _key.Append(')');
 }
Exemple #6
0
        private static DbExpression WithRelationshipsClauseAsCqt(DbExpression row, DbExpression slotValueExpr, IEnumerable <WithRelationship> withRelationships, ProjectedSlot slot)
        {
            List <DbRelatedEntityRef> relatedEntityRefs = new List <DbRelatedEntityRef>();

            WithRelationshipsClauseAsCql(
                // emitWithRelationship action
                (withRelationship) =>
            {
                relatedEntityRefs.Add(withRelationship.AsCqt(row));
            },
                withRelationships,
                slot);

            if (relatedEntityRefs.Count > 0)
            {
                DbNewInstanceExpression typeConstructor = slotValueExpr as DbNewInstanceExpression;
                Debug.Assert(typeConstructor != null && typeConstructor.ResultType.EdmType.BuiltInTypeKind == BuiltInTypeKind.EntityType,
                             "WITH RELATIONSHIP clauses should be specified for entity type constructors only.");
                return(DbExpressionBuilder.CreateNewEntityWithRelationshipsExpression(
                           (EntityType)typeConstructor.ResultType.EdmType,
                           typeConstructor.Arguments,
                           relatedEntityRefs));
            }
            else
            {
                return(slotValueExpr);
            }
        }
Exemple #7
0
        public override Expression Visit(DbNewInstanceExpression expression)
        {
            Type resultType = edmTypeConverter.Convert(expression.ResultType);

            Expression[] args = this.VisitExpressions(expression.Arguments);
            return(this.CreateSelector(args, resultType));
        }
Exemple #8
0
 public override void Visit(DbNewInstanceExpression e)
 {
     Check.NotNull <DbNewInstanceExpression>(e, nameof(e));
     this.VisitExprKind(e.ExpressionKind);
     this._key.Append(':');
     this._key.Append(e.ResultType.EdmType.Identity);
     this._key.Append('(');
     foreach (DbExpression dbExpression in (IEnumerable <DbExpression>)e.Arguments)
     {
         this._key.Append('(');
         dbExpression.Accept((DbExpressionVisitor)this);
         this._key.Append(')');
     }
     if (e.HasRelatedEntityReferences)
     {
         foreach (DbRelatedEntityRef relatedEntityReference in e.RelatedEntityReferences)
         {
             this._key.Append("RE(A(");
             this._key.Append(relatedEntityReference.SourceEnd.DeclaringType.Identity);
             this._key.Append(")(");
             this._key.Append(relatedEntityReference.SourceEnd.Name);
             this._key.Append("->");
             this._key.Append(relatedEntityReference.TargetEnd.Name);
             this._key.Append(")(");
             relatedEntityReference.TargetEntityReference.Accept((DbExpressionVisitor)this);
             this._key.Append("))");
         }
     }
     this._key.Append(')');
 }
Exemple #9
0
        private static DbRelatedEntityRef RelatedEntityRefFromAssociationSetEnd(
            EntityType constructedEntityType,
            DbNewInstanceExpression entityConstructor,
            AssociationSetEnd principalSetEnd,
            ReferentialConstraint fkConstraint)
        {
            EntityType elementType = (EntityType)TypeHelpers.GetEdmType <RefType>(fkConstraint.FromRole.TypeUsage).ElementType;
            IEnumerable <Tuple <string, DbExpression> > source = constructedEntityType.Properties.Select <EdmProperty, Tuple <EdmProperty, DbExpression> >((Func <EdmProperty, int, Tuple <EdmProperty, DbExpression> >)((p, idx) => Tuple.Create <EdmProperty, DbExpression>(p, entityConstructor.Arguments[idx]))).Join <Tuple <EdmProperty, DbExpression>, Tuple <EdmProperty, EdmProperty>, EdmProperty, Tuple <string, DbExpression> >(fkConstraint.FromProperties.Select <EdmProperty, Tuple <EdmProperty, EdmProperty> >((Func <EdmProperty, int, Tuple <EdmProperty, EdmProperty> >)((fp, idx) => Tuple.Create <EdmProperty, EdmProperty>(fp, fkConstraint.ToProperties[idx]))), (Func <Tuple <EdmProperty, DbExpression>, EdmProperty>)(pv => pv.Item1), (Func <Tuple <EdmProperty, EdmProperty>, EdmProperty>)(ft => ft.Item2), (Func <Tuple <EdmProperty, DbExpression>, Tuple <EdmProperty, EdmProperty>, Tuple <string, DbExpression> >)((pv, ft) => Tuple.Create <string, DbExpression>(ft.Item1.Name, pv.Item2)));
            IList <DbExpression> dbExpressionList;

            if (fkConstraint.FromProperties.Count == 1)
            {
                dbExpressionList = (IList <DbExpression>) new DbExpression[1]
                {
                    source.Single <Tuple <string, DbExpression> >().Item2
                };
            }
            else
            {
                Dictionary <string, DbExpression> keyValueMap = source.ToDictionary <Tuple <string, DbExpression>, string, DbExpression>((Func <Tuple <string, DbExpression>, string>)(pav => pav.Item1), (Func <Tuple <string, DbExpression>, DbExpression>)(pav => pav.Item2), (IEqualityComparer <string>)StringComparer.Ordinal);
                dbExpressionList = (IList <DbExpression>)((IEnumerable <string>)elementType.KeyMemberNames).Select <string, DbExpression>((Func <string, DbExpression>)(memberName => keyValueMap[memberName])).ToList <DbExpression>();
            }
            DbRefExpression dbRefExpression = principalSetEnd.EntitySet.CreateRef(elementType, (IEnumerable <DbExpression>)dbExpressionList);

            return(DbExpressionBuilder.CreateRelatedEntityRef(fkConstraint.ToRole, fkConstraint.FromRole, (DbExpression)dbRefExpression));
        }
Exemple #10
0
 /// <summary>
 /// Implements the visitor pattern for <see cref="T:System.Data.Common.CommandTrees.DbNewInstanceExpression"/>.
 /// </summary>
 /// <param name="expression">The <see cref="T:System.Data.Common.CommandTrees.DbNewInstanceExpression"/> that is visited.</param>
 public override void Visit(DbNewInstanceExpression expression)
 {
     foreach (DbExpression e in expression.Arguments)
     {
         e.Accept(this);
     }
 }
Exemple #11
0
        /// <summary>
        /// Performs projection for a single row. Evaluates each projection argument against the specified
        /// row, returning a result with the specified type.
        /// </summary>
        /// <param name="node">Projection expression.</param>
        /// <param name="row">Row to project.</param>
        /// <param name="resultType">Type of the projected row.</param>
        /// <returns>Projected row.</returns>
        private PropagatorResult Project(DbProjectExpression node, PropagatorResult row, TypeUsage resultType)
        {
            EntityUtil.CheckArgumentNull(node, "node");

            Debug.Assert(null != node.Projection, "CQT validates DbProjectExpression.Projection property");

            DbNewInstanceExpression projection = node.Projection as DbNewInstanceExpression;

            if (null == projection)
            {
                throw EntityUtil.NotSupported(System.Data.Entity.Strings.Update_UnsupportedProjection(node.Projection.ExpressionKind));
            }

            // Initialize empty structure containing space for every element of the projection.
            PropagatorResult[] projectedValues = new PropagatorResult[projection.Arguments.Count];

            // Extract value from the input row for every projection argument requested.
            for (int ordinal = 0; ordinal < projectedValues.Length; ordinal++)
            {
                projectedValues[ordinal] = Evaluator.Evaluate(projection.Arguments[ordinal], row, this);
            }

            // Return a new row containing projected values.
            PropagatorResult projectedRow = PropagatorResult.CreateStructuralValue(projectedValues, (StructuralType)resultType.EdmType, false);

            return(projectedRow);
        }
Exemple #12
0
            public override void Visit(DbNewInstanceExpression expression)
            {
                Check.NotNull(expression, "expression");

                base.Visit(expression);
                var type = expression.ResultType.EdmType;

                if (type.BuiltInTypeKind
                    != BuiltInTypeKind.RowType)
                {
                    // restrict initialization of non-row types to the target of the view or complex types
                    // in the target
                    if (!(type == _elementType || (_includeSubtypes && _elementType.IsAssignableFrom(type)))
                        &&
                        !(type.BuiltInTypeKind == BuiltInTypeKind.ComplexType && GetComplexTypes().Contains((ComplexType)type)))
                    {
                        _errors.Add(
                            new EdmSchemaError(
                                Strings.Mapping_UnsupportedInitialization_QueryView(
                                    _setMapping.Set.Name, type.FullName),
                                (int)MappingErrorCode.MappingUnsupportedInitializationQueryView,
                                EdmSchemaErrorSeverity.Error, _setMapping.EntityContainerMapping.SourceLocation, _setMapping.StartLineNumber,
                                _setMapping.StartLinePosition));
                    }
                }
            }
Exemple #13
0
            public override DbExpressionEntitySetInfo Visit(DbNewInstanceExpression expression)
            {
                Check.NotNull(expression, "expression");

                var argumentSetInfos = VisitExpressionList(expression.Arguments);
                var structuralType   = (expression.ResultType.EdmType as StructuralType);

                if (argumentSetInfos != null &&
                    structuralType != null)
                {
                    var structuralTypeSetInfos = new DbExpressionStructuralTypeEntitySetInfo();
                    var i = 0;
                    foreach (var info in argumentSetInfos.entitySetInfos)
                    {
                        structuralTypeSetInfos.Add(structuralType.Members[i].Name, info);
                        i++;
                    }
                    //Since we already validated the query view, the only association type that
                    //can be constructed is the type for the set we are validating the mapping for.
                    if (expression.ResultType.EdmType.BuiltInTypeKind
                        == BuiltInTypeKind.AssociationType)
                    {
                        ValidateEntitySetsMappedForAssociationSetMapping(structuralTypeSetInfos);
                    }
                    return(structuralTypeSetInfos);
                }
                return(null);
            }
Exemple #14
0
 public override void Visit(DbNewInstanceExpression expression)
 {
     Write(expression);
     _depth++;
     Write("Arguments", expression.Arguments);
     _depth--;
 }
        public override DbExpression Visit(DbNewInstanceExpression expression)
        {
            DebugCheck.NotNull(expression);

            // Update the returning new instance expression with the column
            // names from the sproc result binding.
            var arguments
                = (from propertyExpression in expression.Arguments.Cast <DbPropertyExpression>()
                   let resultBinding
                       = _currentFunctionMapping
                         .ResultBindings
                         .Single(
                             rb => (from esm in _entityContainerMapping.EntitySetMappings
                                    from etm in esm.EntityTypeMappings
                                    from mf in etm.MappingFragments
                                    from pm in mf.Properties.OfType <StorageScalarPropertyMapping>()
                                    where
                                    pm.ColumnProperty.EdmEquals(propertyExpression.Property) &&
                                    pm.ColumnProperty.DeclaringType.EdmEquals(propertyExpression.Property.DeclaringType)
                                    select pm.EdmProperty)
                             .Contains(rb.Property))
                         select new KeyValuePair <string, DbExpression>(resultBinding.ColumnName, propertyExpression))
                  .ToList();

            return(DbExpressionBuilder.NewRow(arguments));
        }
        public static FieldDescription[] GetReturningFields(
            DbExpression returning)
        {
            // Find the returning properties
            DbNewInstanceExpression returnExpression = returning as DbNewInstanceExpression;

            if (returnExpression == null)
            {
                throw new NotSupportedException(
                          "The type of the Returning properties is not DbNewInstanceExpression");
            }

            List <FieldDescription> result = new List <FieldDescription>();

            // Add the returning property names
            foreach (DbPropertyExpression propertyExpression in returnExpression.Arguments)
            {
                PrimitiveType propertyType =
                    propertyExpression.ResultType.EdmType as PrimitiveType;

                string name = propertyExpression.Property.GetColumnName();
                Type   type = propertyType.ClrEquivalentType;

                result.Add(new FieldDescription(name, type));
            }

            return(result.ToArray());
        }
            public override ViewValidator.DbExpressionEntitySetInfo Visit(
                DbNewInstanceExpression expression)
            {
                Check.NotNull <DbNewInstanceExpression>(expression, nameof(expression));
                ViewValidator.DbExpressionMemberCollectionEntitySetInfo collectionEntitySetInfo = this.VisitExpressionList(expression.Arguments);
                StructuralType edmType = expression.ResultType.EdmType as StructuralType;

                if (collectionEntitySetInfo == null || edmType == null)
                {
                    return((ViewValidator.DbExpressionEntitySetInfo)null);
                }
                ViewValidator.DbExpressionStructuralTypeEntitySetInfo setInfos = new ViewValidator.DbExpressionStructuralTypeEntitySetInfo();
                int index = 0;

                foreach (ViewValidator.DbExpressionEntitySetInfo entitySetInfo in collectionEntitySetInfo.entitySetInfos)
                {
                    setInfos.Add(edmType.Members[index].Name, entitySetInfo);
                    ++index;
                }
                if (expression.ResultType.EdmType.BuiltInTypeKind == BuiltInTypeKind.AssociationType)
                {
                    this.ValidateEntitySetsMappedForAssociationSetMapping(setInfos);
                }
                return((ViewValidator.DbExpressionEntitySetInfo)setInfos);
            }
Exemple #18
0
 /// <summary>
 /// DbNewInstanceExpression is allowed as a child of DbProjectExpression only.
 /// If anyone else is the parent, we throw.
 /// We also perform special casing for collections - where we could convert
 /// them into Unions
 ///
 /// <see cref="VisitNewInstanceExpression"/> for the actual implementation.
 ///
 /// </summary>
 /// <param name="e"></param>
 /// <returns></returns>
 public override ISqlFragment Visit(DbNewInstanceExpression e)
 {
     if (MetadataHelpers.IsCollectionType(e.ResultType))
     {
         return(VisitCollectionConstructor(e));
     }
     throw new NotSupportedException();
 }
 private static string GetGuidArgs(DbNewInstanceExpression returning)
 {
     return((from arg in returning.Arguments
             where ((DbPropertyExpression)arg).Property.IsStoreGeneratedIdentity &&
             ((DbPropertyExpression)arg).Property.TypeUsage.EdmType.Name == "guid"
             select((DbPropertyExpression)arg).Property.Name
             ).FirstOrDefault() ?? string.Empty);
 }
Exemple #20
0
        public override object Visit(DbNewInstanceExpression expression)
        {
            foreach (var arg in expression.Arguments)
            {
                this.Visit(arg);
            }

            return(null);
        }
Exemple #21
0
        /// <summary>
        /// Translate a NewInstance(Element(X)) expression into
        ///   "select top(1) * from X"
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        private ISqlFragment VisitCollectionConstructor(DbNewInstanceExpression e)
        {
            Debug.Assert(e.Arguments.Count <= 1);

            if (e.Arguments.Count == 1 && e.Arguments[0].ExpressionKind == DbExpressionKind.Element)
            {
                DbElementExpression elementExpr = e.Arguments[0] as DbElementExpression;
                SqlSelectStatement  result      = VisitExpressionEnsureSqlStatement(elementExpr.Argument);

                if (!IsCompatible(result, DbExpressionKind.Element))
                {
                    Symbol    fromSymbol;
                    TypeUsage inputType = MetadataHelpers.GetElementTypeUsage(elementExpr.Argument.ResultType);

                    result = CreateNewSelectStatement(result, "element", inputType, out fromSymbol);
                    AddFromSymbol(result, "element", fromSymbol, false);
                }
                result.Top.SetTopCount(1);
                return(result);
            }


            // Otherwise simply build this out as a union-all ladder
            CollectionType collectionType = MetadataHelpers.GetEdmType <CollectionType>(e.ResultType);

            Debug.Assert(collectionType != null);
            bool isScalarElement = MetadataHelpers.IsPrimitiveType(collectionType.TypeUsage);

            SqlBuilder resultSql = new SqlBuilder();
            string     separator = "";

            // handle empty table
            if (e.Arguments.Count == 0)
            {
                Debug.Assert(isScalarElement);
                resultSql.Append(" select cast(null as ");
                resultSql.Append(MetadataHelpers.GetSqlPrimitiveType(collectionType.TypeUsage));
                resultSql.Append(") as x from (select 1) as y where 1=0");
            }

            foreach (DbExpression arg in e.Arguments)
            {
                resultSql.Append(separator);
                resultSql.Append(" select ");
                resultSql.Append(arg.Accept(this));
                // For scalar elements, no alias is appended yet. Add this.
                if (isScalarElement)
                {
                    resultSql.Append(" as x ");
                }
                separator = " union all ";
            }

            return(resultSql);
        }
 /// <summary>
 /// Constructs a new pattern that is matched iff the argument expression is a <see cref="DbNewInstanceExpression"/> with arguments that match the specified collection pattern
 /// </summary>
 internal static Func <DbExpression, bool> MatchNewInstance(Func <IEnumerable <DbExpression>, bool> argumentsPattern)
 {
     return(e => { if (e.ExpressionKind != DbExpressionKind.NewInstance)
                   {
                       return false;
                   }
                   else
                   {
                       DbNewInstanceExpression newInst = (DbNewInstanceExpression)e; return argumentsPattern(newInst.Arguments);
                   } });
 }
Exemple #23
0
        public override LegacyCommandTrees.DbExpression Visit(DbNewInstanceExpression expression)
        {
            Debug.Assert(expression != null, "expression != null");
            Debug.Assert(
                expression.ResultType.EdmType.BuiltInTypeKind == BuiltInTypeKind.CollectionType ||
                expression.ResultType.EdmType.BuiltInTypeKind == BuiltInTypeKind.RowType,
                "Only collection and row types are supported");

            return(expression.ResultType.EdmType.BuiltInTypeKind == BuiltInTypeKind.CollectionType
                       ? CreateNewCollectionInstance(expression)
                       : CreateNewRowTypeInstance(expression));
        }
Exemple #24
0
        /// <summary>
        /// Implements the visitor pattern for <see cref="T:System.Data.Common.CommandTrees.DbNewInstanceExpression"/>.
        /// </summary>
        /// <param name="expression">The <see cref="T:System.Data.Common.CommandTrees.DbNewInstanceExpression"/> that is visited.</param>
        public override void Visit(DbNewInstanceExpression expression)
        {
            if (expression == null)
            {
                throw new ArgumentNullException("expression");
            }

            foreach (DbExpression e in expression.Arguments)
            {
                e.Accept(this);
            }
        }
            public override void Visit(DbNewInstanceExpression expression)
            {
                Check.NotNull <DbNewInstanceExpression>(expression, nameof(expression));
                base.Visit(expression);
                EdmType edmType = expression.ResultType.EdmType;

                if (edmType.BuiltInTypeKind == BuiltInTypeKind.RowType || edmType == this._elementType || this._includeSubtypes && this._elementType.IsAssignableFrom(edmType) || edmType.BuiltInTypeKind == BuiltInTypeKind.ComplexType && this.GetComplexTypes().Contains <ComplexType>((ComplexType)edmType))
                {
                    return;
                }
                this._errors.Add(new EdmSchemaError(Strings.Mapping_UnsupportedInitialization_QueryView((object)this._setMapping.Set.Name, (object)edmType.FullName), 2074, EdmSchemaErrorSeverity.Error, this._setMapping.EntityContainerMapping.SourceLocation, this._setMapping.StartLineNumber, this._setMapping.StartLinePosition));
            }
            public override void Visit(DbNewInstanceExpression newInstanceExpression)
            {
                ReadOnlyMetadataCollection <EdmProperty> properties = ((RowType)newInstanceExpression.ResultType.EdmType).Properties;

                for (int index = 0; index < properties.Count; ++index)
                {
                    this._select.Append(this._select.Length == 0 ? "SELECT " : ", ");
                    this._nextPropertyAlias = properties[index].Name;
                    newInstanceExpression.Arguments[index].Accept((DbExpressionVisitor)this);
                }
                this._nextPropertyAlias = (string)null;
            }
Exemple #27
0
        private static DbRelatedEntityRef RelatedEntityRefFromAssociationSetEnd(
            EntityType constructedEntityType, DbNewInstanceExpression entityConstructor, AssociationSetEnd principalSetEnd,
            ReferentialConstraint fkConstraint)
        {
            var principalEntityType = (EntityType)TypeHelpers.GetEdmType <RefType>(fkConstraint.FromRole.TypeUsage).ElementType;
            IList <DbExpression> principalKeyValues = null;

            // Create Entity Property/DbExpression value pairs from the entity constructor DbExpression,
            // then join these with the principal/dependent property pairs from the FK constraint
            // to produce principal property name/DbExpression value pairs from which to create the principal ref.
            //
            // Ideally the code would be as below, but anonymous types break asmmeta:
            //var keyPropAndValue =
            //    from pv in constructedEntityType.Properties.Select((p, idx) => new { DependentProperty = p, Value = entityConstructor.Arguments[idx] })
            //    join ft in fkConstraint.FromProperties.Select((fp, idx) => new { PrincipalProperty = fp, DependentProperty = fkConstraint.ToProperties[idx] })
            //    on pv.DependentProperty equals ft.DependentProperty
            //    select new { PrincipalProperty = ft.PrincipalProperty.Name, Value = pv.Value };
            //
            var keyPropAndValue =
                from pv in constructedEntityType.Properties.Select((p, idx) => Tuple.Create(p, entityConstructor.Arguments[idx]))
                // new { DependentProperty = p, Value = entityConstructor.Arguments[idx] })
                join ft in fkConstraint.FromProperties.Select((fp, idx) => Tuple.Create(fp, fkConstraint.ToProperties[idx]))
                //new { PrincipalProperty = fp, DependentProperty = fkConstraint.ToProperties[idx] })
                on pv.Item1 equals ft.Item2
                //pv.DependentProperty equals ft.DependentProperty
                select Tuple.Create(ft.Item1.Name, pv.Item2); // new { PrincipalProperty = ft.PrincipalProperty.Name, Value = pv.Value };

            // If there is only a single property in the principal's key, then there is no ordering concern.
            // Otherwise, create a dictionary of principal key property name to DbExpression value so that
            // when used as the arguments to the ref expression, the dependent property values - used here
            // as principal key property values - are in the correct order, which is the same order as the
            // key members themselves.
            //
            if (fkConstraint.FromProperties.Count == 1)
            {
                var singleKeyNameAndValue = keyPropAndValue.Single();
                Debug.Assert(singleKeyNameAndValue.Item1 == fkConstraint.FromProperties[0].Name, "Unexpected single key property name");
                principalKeyValues = new[] { singleKeyNameAndValue.Item2 };
            }
            else
            {
                var keyValueMap = keyPropAndValue.ToDictionary(pav => pav.Item1, pav => pav.Item2, StringComparer.Ordinal);
                principalKeyValues = principalEntityType.KeyMemberNames.Select(memberName => keyValueMap[memberName]).ToList();
            }

            // Create the ref to the principal entity based on the (now correctly ordered) key value expressions.
            //
            var principalRef = principalSetEnd.EntitySet.CreateRef(principalEntityType, principalKeyValues);
            var result       = DbExpressionBuilder.CreateRelatedEntityRef(fkConstraint.ToRole, fkConstraint.FromRole, principalRef);

            return(result);
        }
        public override DbExpression Visit(DbNewInstanceExpression expression)
        {
            var argments = expression.Arguments.Select(t =>
            {
                if (t is DbPropertyExpression propertyArg && _typeToTrim.Contains(propertyArg.Property.TypeUsage.EdmType.Name))
                {
                    return(EdmFunctions.Trim(t));
                }
                return(t);
            });

            return(DbExpressionBuilder.New(expression.ResultType, argments));
        }
        private static bool ExpressionsCompatible(DbExpression x, DbExpression y)
        {
            if (x.ExpressionKind != y.ExpressionKind)
            {
                return(false);
            }
            switch (x.ExpressionKind)
            {
            case DbExpressionKind.NewInstance:
                DbNewInstanceExpression instanceExpression1 = (DbNewInstanceExpression)x;
                DbNewInstanceExpression instanceExpression2 = (DbNewInstanceExpression)y;
                if (!instanceExpression1.ResultType.EdmType.EdmEquals((MetadataItem)instanceExpression2.ResultType.EdmType))
                {
                    return(false);
                }
                for (int index = 0; index < instanceExpression1.Arguments.Count; ++index)
                {
                    if (!DiscriminatorMap.ExpressionsCompatible(instanceExpression1.Arguments[index], instanceExpression2.Arguments[index]))
                    {
                        return(false);
                    }
                }
                return(true);

            case DbExpressionKind.Property:
                DbPropertyExpression propertyExpression1 = (DbPropertyExpression)x;
                DbPropertyExpression propertyExpression2 = (DbPropertyExpression)y;
                if (propertyExpression1.Property == propertyExpression2.Property)
                {
                    return(DiscriminatorMap.ExpressionsCompatible(propertyExpression1.Instance, propertyExpression2.Instance));
                }
                return(false);

            case DbExpressionKind.Ref:
                DbRefExpression dbRefExpression1 = (DbRefExpression)x;
                DbRefExpression dbRefExpression2 = (DbRefExpression)y;
                if (dbRefExpression1.EntitySet.EdmEquals((MetadataItem)dbRefExpression2.EntitySet))
                {
                    return(DiscriminatorMap.ExpressionsCompatible(dbRefExpression1.Argument, dbRefExpression2.Argument));
                }
                return(false);

            case DbExpressionKind.VariableReference:
                return(((DbVariableReferenceExpression)x).VariableName == ((DbVariableReferenceExpression)y).VariableName);

            default:
                return(false);
            }
        }
            public override DbExpression Visit(DbNewInstanceExpression expression)
            {
                var arguments = expression.Arguments.Select(a =>
                {
                    var propertyArg = a as DbPropertyExpression;
                    if (propertyArg != null && _typesToTrim.Contains(propertyArg.Property.TypeUsage.EdmType.Name))
                    {
                        return(EdmFunctions.Trim(a));
                    }

                    return(a);
                });

                return(DbExpressionBuilder.New(expression.ResultType, arguments));
            }
Exemple #31
0
        internal void AppendReturning(DbNewInstanceExpression expression)
        {
            Append(" RETURNING ");//Don't put () around columns it will probably have unwanted effect
            bool first = true;

            foreach (var returingProperty in expression.Arguments)
            {
                if (!first)
                {
                    Append(",");
                }
                Append(SqlBaseGenerator.QuoteIdentifier((returingProperty as DbPropertyExpression).Property.Name));
                first = false;
            }
        }
            public override DbExpression Visit(DbNewInstanceExpression expression)
            {
                var arguments = expression.Arguments.Select(a =>
                {
                    var propertyArg = a as DbPropertyExpression;

                    if (propertyArg != null && _typesToTrim.Contains(propertyArg.Property.TypeUsage.EdmType.Name))
                    {
                        return EdmFunctions.Trim(a);
                    }

                    return a;
                });

                return DbExpressionBuilder.New(expression.ResultType, arguments);
            }
        private static DbRelatedEntityRef RelatedEntityRefFromAssociationSetEnd(EntityType constructedEntityType, DbNewInstanceExpression entityConstructor, AssociationSetEnd principalSetEnd, ReferentialConstraint fkConstraint)
        {
            EntityType principalEntityType = (EntityType)TypeHelpers.GetEdmType<RefType>(fkConstraint.FromRole.TypeUsage).ElementType;
            IList<DbExpression> principalKeyValues = null;
            
            // Create Entity Property/DbExpression value pairs from the entity constructor DbExpression,
            // then join these with the principal/dependent property pairs from the FK constraint
            // to produce principal property name/DbExpression value pairs from which to create the principal ref.
            //
            // Ideally the code would be as below, but anonymous types break asmmeta:
            //var keyPropAndValue =
            //    from pv in constructedEntityType.Properties.Select((p, idx) => new { DependentProperty = p, Value = entityConstructor.Arguments[idx] })
            //    join ft in fkConstraint.FromProperties.Select((fp, idx) => new { PrincipalProperty = fp, DependentProperty = fkConstraint.ToProperties[idx] })
            //    on pv.DependentProperty equals ft.DependentProperty
            //    select new { PrincipalProperty = ft.PrincipalProperty.Name, Value = pv.Value };
            //
            var keyPropAndValue =
                from pv in constructedEntityType.Properties.Select((p, idx) => Tuple.Create(p, entityConstructor.Arguments[idx])) // new { DependentProperty = p, Value = entityConstructor.Arguments[idx] })
                join ft in fkConstraint.FromProperties.Select((fp, idx) => Tuple.Create(fp, fkConstraint.ToProperties[idx])) //new { PrincipalProperty = fp, DependentProperty = fkConstraint.ToProperties[idx] })
                on pv.Item1 equals ft.Item2 //pv.DependentProperty equals ft.DependentProperty
                select Tuple.Create(ft.Item1.Name, pv.Item2); // new { PrincipalProperty = ft.PrincipalProperty.Name, Value = pv.Value };

            // If there is only a single property in the principal's key, then there is no ordering concern.
            // Otherwise, create a dictionary of principal key property name to DbExpression value so that
            // when used as the arguments to the ref expression, the dependent property values - used here
            // as principal key property values - are in the correct order, which is the same order as the
            // key members themselves.
            //
            if (fkConstraint.FromProperties.Count == 1)
            {
                var singleKeyNameAndValue = keyPropAndValue.Single();
                Debug.Assert(singleKeyNameAndValue.Item1 == fkConstraint.FromProperties[0].Name, "Unexpected single key property name");
                principalKeyValues = new[] { singleKeyNameAndValue.Item2 };
            }
            else
            {
                var keyValueMap = keyPropAndValue.ToDictionary(pav => pav.Item1, pav => pav.Item2, StringComparer.Ordinal);
                principalKeyValues = principalEntityType.KeyMemberNames.Select(memberName => keyValueMap[memberName]).ToList();
            }
                        
            // Create the ref to the principal entity based on the (now correctly ordered) key value expressions.
            //
            DbRefExpression principalRef = principalSetEnd.EntitySet.CreateRef(principalEntityType, principalKeyValues);
            DbRelatedEntityRef result = DbExpressionBuilder.CreateRelatedEntityRef(fkConstraint.ToRole, fkConstraint.FromRole, principalRef);

            return result;
        }
        /// <summary>
        /// Implements the visitor pattern for <see cref="T:System.Data.Common.CommandTrees.DbNewInstanceExpression"/>.
        /// </summary>
        /// <param name="expression">The <see cref="T:System.Data.Common.CommandTrees.DbNewInstanceExpression"/> that is visited.</param>
        public override void Visit(DbNewInstanceExpression expression)
        {
            if (expression == null)
            {
                throw new ArgumentNullException("expression");
            }

            foreach (DbExpression e in expression.Arguments)
            {
                e.Accept(this);
            }
        }
 public override void Visit(DbNewInstanceExpression e)
 {
     VisitExprKind(e.ExpressionKind);
     _key.Append(':');
     _key.Append(e.ResultType.EdmType.Identity);
     _key.Append('(');
     foreach (var a in e.Arguments)
     {
         _key.Append('(');
         a.Accept(this);
         _key.Append(')');
     }
     if (e.HasRelatedEntityReferences)
     {
         foreach (var relatedRef in e.RelatedEntityReferences)
         {
             _key.Append("RE(A(");
             _key.Append(relatedRef.SourceEnd.DeclaringType.Identity);
             _key.Append(")(");
             _key.Append(relatedRef.SourceEnd.Name);
             _key.Append("->");
             _key.Append(relatedRef.TargetEnd.Name);
             _key.Append(")(");
             relatedRef.TargetEntityReference.Accept(this);
             _key.Append("))");
         }
     }
     _key.Append(')');
 }
        /// <summary>
        ///     Visitor pattern method for <see cref="DbNewInstanceExpression" />.
        /// </summary>
        /// <param name="expression"> The DbNewInstanceExpression that is being visited. </param>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="expression" />
        ///     is null
        /// </exception>
        public override void Visit(DbNewInstanceExpression expression)
        {
            Check.NotNull(expression, "expression");

            VisitExpressionList(expression.Arguments);
            if (expression.HasRelatedEntityReferences)
            {
                Debug.Assert(
                    expression.RelatedEntityReferences != null,
                    "HasRelatedEntityReferences returned true for null RelatedEntityReferences list?");
                VisitRelatedEntityReferenceList(expression.RelatedEntityReferences);
            }
        }
 /// <summary>
 ///     Visitor pattern method for DbNewInstanceExpression.
 /// </summary>
 /// <param name="expression"> The DbNewInstanceExpression that is being visited. </param>
 public abstract void Visit(DbNewInstanceExpression expression);
        public override SqlFragment Visit(DbNewInstanceExpression expression)
        {
            Debug.Assert(expression.ResultType.EdmType is CollectionType);

            SelectStatement s = new SelectStatement();

            ColumnFragment c = new ColumnFragment(null, null);
            if (expression.Arguments.Count != 0)
                c.Literal = (LiteralFragment)expression.Arguments[0].Accept(this);
            else
                c.Literal = new LiteralFragment("NULL");
            c.ColumnAlias = "X";
            s.Columns.Add(c);
            return s;
        }
 public override void Visit(DbNewInstanceExpression expression) { }
 public override void Visit(DbNewInstanceExpression e)
 {
     Begin(e);
     Dump(e.Arguments, "Arguments", "Argument");
     if (e.HasRelatedEntityReferences)
     {
         Begin("RelatedEntityReferences");
         foreach (DbRelatedEntityRef relatedRef in e.RelatedEntityReferences)
         {
             Begin("DbRelatedEntityRef");
             Dump(relatedRef.SourceEnd, "SourceEnd");
             Dump(relatedRef.TargetEnd, "TargetEnd");
             Dump(relatedRef.TargetEntityReference, "TargetEntityReference");
             End("DbRelatedEntityRef");
         }
         End("RelatedEntityReferences");
     }
     End(e);
 }
 /// <summary>
 /// Visitor pattern method for <see cref="DbNewInstanceExpression"/>.
 /// </summary>
 /// <param name="expression">The DbNewInstanceExpression that is being visited.</param>
 /// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
 public override void Visit(DbNewInstanceExpression expression)
 {
     // #433613: PreSharp warning 56506: Parameter 'expression' to this public method must be validated: A null-dereference can occur here.
     EntityUtil.CheckArgumentNull(expression, "expression");
     VisitExpressionList(expression.Arguments);
     if (expression.HasRelatedEntityReferences)
     {
         Debug.Assert(expression.RelatedEntityReferences != null, "HasRelatedEntityReferences returned true for null RelatedEntityReferences list?");
         this.VisitRelatedEntityReferenceList(expression.RelatedEntityReferences);
     }
 }
Exemple #42
0
 internal void AppendReturning(DbNewInstanceExpression expression)
 {
     Append(" RETURNING ");//Don't put () around columns it will probably have unwanted effect
     bool first = true;
     foreach (var returingProperty in expression.Arguments)
     {
         if (!first)
             Append(",");
         Append(SqlBaseGenerator.QuoteIdentifier((returingProperty as DbPropertyExpression).Property.Name));
         first = false;
     }
 }
            public override void Visit(DbNewInstanceExpression newInstanceExpression)
            {
                DebugCheck.NotNull(newInstanceExpression);

                var properties = ((RowType)newInstanceExpression.ResultType.EdmType).Properties;

                for (var i = 0; i < properties.Count; i++)
                {
                    _select.Append(_select.Length == 0 ? "SELECT " : ", ");

                    _nextPropertyAlias = properties[i].Name;

                    newInstanceExpression.Arguments[i].Accept(this);
                }

                _nextPropertyAlias = null;
            }
            public override void Visit(DbNewInstanceExpression expression)
            {
                Check.NotNull(expression, "expression");

                // assumes all arguments are self-describing (no need to use aliases
                // because no renames are ever used in the projection)

                var first = true;

                foreach (var argument in expression.Arguments)
                {
                    var property = ((DbPropertyExpression)argument).Property;

                    var variableAssignment
                        = (_localVariableBindings != null)
                              ? (_localVariableBindings.Contains(property)
                                     ? "@" + property.Name + " = "
                                     : null)
                              : string.Empty;

                    if (variableAssignment != null)
                    {
                        if (first)
                        {
                            first = false;
                        }
                        else
                        {
                            _commandText.Append(", ");
                        }

                        _commandText.Append(variableAssignment);

                        argument.Accept(this);
                    }
                }
            }
 /// <summary>
 ///     Visitor pattern method for <see cref="DbNewInstanceExpression" />.
 /// </summary>
 /// <param name="expression"> The DbNewInstanceExpression that is being visited. </param>
 /// <exception cref="ArgumentNullException">
 ///     <paramref name="expression" />
 ///     is null
 /// </exception>
 public override void Visit(DbNewInstanceExpression expression)
 {
     // #433613: PreSharp warning 56506: Parameter 'expression' to this public method must be validated: A null-dereference can occur here.
     VisitExpressionList(Check.NotNull(expression, "expression").Arguments);
 }
 public override DbExpression Visit(DbNewInstanceExpression expression)
 {
     System.Diagnostics.Debug.Print("Visit(DbNewInstanceExpression): {0}", expression);
     return base.Visit(expression);
 }
 public override void Visit(DbNewInstanceExpression expression)
 {
     // assumes all arguments are self-describing (no need to use aliases
     // because no renames are ever used in the projection)
     var first = true;
     foreach (var argument in expression.Arguments)
     {
         if (first)
         {
             first = false;
         }
         else
         {
             _commandText.Append(", ");
         }
         argument.Accept(this);
     }
 }
 public override void Visit(DbNewInstanceExpression expression)
 {
     Contract.Requires(expression != null);
 }