internal StorageModificationFunctionMapping(
            EntitySetBase entitySet,
            EntityTypeBase entityType,
            EdmFunction function,
            IEnumerable<StorageModificationFunctionParameterBinding> parameterBindings,
            FunctionParameter rowsAffectedParameter,
            IEnumerable<StorageModificationFunctionResultBinding> resultBindings)
        {
            //Contract.Requires(entitySet != null);
            //Contract.Requires(function != null);
            //Contract.Requires(parameterBindings != null);

            Function = function;
            RowsAffectedParameter = rowsAffectedParameter;
            ParameterBindings = parameterBindings.ToList().AsReadOnly();
            if (null != resultBindings)
            {
                var bindings = resultBindings.ToList();
                if (0 < bindings.Count)
                {
                    ResultBindings = bindings.AsReadOnly();
                }
            }
            CollocatedAssociationSetEnds =
                GetReferencedAssociationSetEnds(entitySet as EntitySet, entityType as EntityType, parameterBindings)
                    .ToList()
                    .AsReadOnly();
        }
        public void WriteFunctionElementHeader_should_not_write_return_type_attribute_for_non_primitive_return_type()
        {
            var fixture = new Fixture();

            var returnParameterType = TypeUsage.CreateDefaultTypeUsage(new RowType());

            var function = new EdmFunction(
                "Foo",
                "Bar",
                DataSpace.SSpace,
                new EdmFunctionPayload
                    {
                        Schema = "dbo",
                        ReturnParameters =
                            new[]
                                {
                                    new FunctionParameter(
                                        "r",
                                        returnParameterType,
                                        ParameterMode.ReturnValue)
                                }
                    });

            fixture.Writer.WriteFunctionElementHeader(function);

            Assert.Equal(
                "<Function Name=\"Foo\" Aggregate=\"false\" BuiltIn=\"false\" NiladicFunction=\"false\" IsComposable=\"true\" ParameterTypeSemantics=\"AllowImplicitConversion\" Schema=\"dbo\"",
                fixture.ToString());
        }
Example #3
0
        public void VisitEdmEntityContainer_visits_function_imports()
        {
            var functionPayload =
                new EdmFunctionPayload
                    {
                        IsFunctionImport = true
                    };

            var functionImport =
                new EdmFunction("f", "N", DataSpace.CSpace, functionPayload);

            var model = new EdmModel(DataSpace.CSpace);
            model.Container.AddFunctionImport(functionImport);

            var visitorMock =
                new Mock<EdmModelVisitor>
                    {
                        CallBase = true
                    };

            visitorMock.Object.VisitEdmModel(model);

            visitorMock.Verify(v => v.VisitFunctionImports(model.Container, It.IsAny<IEnumerable<EdmFunction>>()), Times.Once());
            visitorMock.Verify(v => v.VisitFunctionImport(functionImport), Times.Once());
        }
Example #4
0
        public void VisitEdmFunction_should_visit_edm_function_parameters()
        {
            var visitorMock
                = new Mock<EdmModelVisitor>
                      {
                          CallBase = true
                      };

            var functionParameter
                = new FunctionParameter(
                    "P",
                    TypeUsage.Create(PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String)),
                    ParameterMode.In);

            var functionPayload
                = new EdmFunctionPayload
                      {
                          Parameters = new[] { functionParameter }
                      };

            var function = new EdmFunction("F", "N", DataSpace.SSpace, functionPayload);

            visitorMock.Object.VisitEdmFunction(function);

            visitorMock.Verify(v => v.VisitMetadataItem(functionParameter), Times.Once());
            visitorMock.Verify(v => v.VisitFunctionParameter(functionParameter), Times.Once());
        }
        internal void AddAggregate(
            PrimitiveTypeKind returnTypeKind, string aggregateFunctionName, PrimitiveTypeKind collectionArgumentElementTypeKind)
        {
            DebugCheck.NotEmpty(aggregateFunctionName);

            var returnParameter = CreateReturnParameter(returnTypeKind);
            var collectionParameter = CreateAggregateParameter(collectionArgumentElementTypeKind);

            var function = new EdmFunction(
                aggregateFunctionName,
                EdmConstants.EdmNamespace,
                DataSpace.CSpace,
                new EdmFunctionPayload
                    {
                        IsAggregate = true,
                        IsBuiltIn = true,
                        ReturnParameters = new[] { returnParameter },
                        Parameters = new FunctionParameter[1] { collectionParameter },
                        IsFromProviderManifest = true,
                    });

            function.SetReadOnly();

            functions.Add(function);
        }
        internal StorageModificationFunctionMapping(
            EntitySetBase entitySet,
            EntityTypeBase entityType,
            EdmFunction function,
            IEnumerable<StorageModificationFunctionParameterBinding> parameterBindings,
            FunctionParameter rowsAffectedParameter,
            IEnumerable<StorageModificationFunctionResultBinding> resultBindings)
        {
            DebugCheck.NotNull(entitySet);
            DebugCheck.NotNull(function);
            DebugCheck.NotNull(parameterBindings);

            _function = function;
            _rowsAffectedParameter = rowsAffectedParameter;

            ParameterBindings = parameterBindings.ToList().AsReadOnly();

            if (null != resultBindings)
            {
                var bindings = resultBindings.ToList();

                if (0 < bindings.Count)
                {
                    ResultBindings = bindings.AsReadOnly();
                }
            }

            CollocatedAssociationSetEnds =
                GetReferencedAssociationSetEnds(entitySet as EntitySet, entityType as EntityType, parameterBindings)
                    .ToList()
                    .AsReadOnly();
        }
Example #7
0
        /// <summary>
        /// Reports function overload resolution error.
        /// </summary>
        internal static void ReportFunctionOverloadError(AST.MethodExpr functionExpr, EdmFunction functionType, List<TypeUsage> argTypes)
        {
            string strDelim = "";
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append(functionType.Name).Append("(");
            for (int i = 0 ; i < argTypes.Count ; i++)
            {
                sb.Append(strDelim);
                sb.Append(argTypes[i] != null ? argTypes[i].EdmType.FullName : "NULL");
                strDelim = ", ";
            }
            sb.Append(")");

            Func<object, object, object, string> formatString;
            if (TypeSemantics.IsAggregateFunction(functionType))
            {
                formatString = TypeHelpers.IsCanonicalFunction(functionType) ? 
                                            (Func<object, object, object, string>)System.Data.Entity.Strings.NoCanonicalAggrFunctionOverloadMatch :
                                            (Func<object, object, object, string>)System.Data.Entity.Strings.NoAggrFunctionOverloadMatch;
            }
            else
            {
                formatString = TypeHelpers.IsCanonicalFunction(functionType) ?
                                            (Func<object, object, object, string>)System.Data.Entity.Strings.NoCanonicalFunctionOverloadMatch :
                                            (Func<object, object, object, string>)System.Data.Entity.Strings.NoFunctionOverloadMatch;
            }

            throw EntityUtil.EntitySqlError(functionExpr.ErrCtx.CommandText,
                                 formatString(functionType.NamespaceName, functionType.Name, sb.ToString()),
                                 functionExpr.ErrCtx.InputPosition,
                                 System.Data.Entity.Strings.CtxFunction(functionType.Name),
                                 false /* loadContextInfoFromResource */);
        }
        /// <summary>
        ///     Reports function overload resolution error.
        /// </summary>
        internal static void ReportFunctionOverloadError(MethodExpr functionExpr, EdmFunction functionType, List<TypeUsage> argTypes)
        {
            var strDelim = "";
            var sb = new StringBuilder();
            sb.Append(functionType.Name).Append("(");
            for (var i = 0; i < argTypes.Count; i++)
            {
                sb.Append(strDelim);
                sb.Append(argTypes[i] != null ? argTypes[i].EdmType.FullName : "NULL");
                strDelim = ", ";
            }
            sb.Append(")");

            Func<object, object, object, string> formatString;
            if (TypeSemantics.IsAggregateFunction(functionType))
            {
                formatString = TypeHelpers.IsCanonicalFunction(functionType)
                                   ? Strings.NoCanonicalAggrFunctionOverloadMatch
                                   : (Func<object, object, object, string>)Strings.NoAggrFunctionOverloadMatch;
            }
            else
            {
                formatString = TypeHelpers.IsCanonicalFunction(functionType)
                                   ? Strings.NoCanonicalFunctionOverloadMatch
                                   : (Func<object, object, object, string>)Strings.NoFunctionOverloadMatch;
            }

            throw EntitySqlException.Create(
                functionExpr.ErrCtx.CommandText,
                formatString(functionType.NamespaceName, functionType.Name, sb.ToString()),
                functionExpr.ErrCtx.InputPosition,
                Strings.CtxFunction(functionType.Name),
                false,
                null);
        }
        public void Can_clear_modification_function_mappings()
        {
            var entityType = new EntityType("E", "N", DataSpace.CSpace);
            var entitySet = new EntitySet("S", "N", null, null, entityType);
            var function = new EdmFunction("F", "N", DataSpace.SSpace, new EdmFunctionPayload());

            var container = new EntityContainer("C", DataSpace.CSpace);
            container.AddEntitySetBase(entitySet);

            var entitySetMapping =
                new StorageEntitySetMapping(
                    entitySet,
                    new StorageEntityContainerMapping(container));

            var functionMapping =
                new StorageModificationFunctionMapping(
                    entitySet,
                    entityType,
                    function,
                    Enumerable.Empty<StorageModificationFunctionParameterBinding>(),
                    null,
                    null);

            var entityFunctionMappings =
                new StorageEntityTypeModificationFunctionMapping(entityType, functionMapping, null, null);

            entitySetMapping.AddModificationFunctionMapping(entityFunctionMappings);

            Assert.Equal(1, entitySetMapping.ModificationFunctionMappings.Count());

            entitySetMapping.ClearModificationFunctionMappings();

            Assert.Equal(0, entitySetMapping.ModificationFunctionMappings.Count());
        }
        internal FunctionImportMappingNonComposable(
            EdmFunction functionImport,
            EdmFunction targetFunction,
            List<List<FunctionImportStructuralTypeMapping>> structuralTypeMappingsList,
            ItemCollection itemCollection)
            : base(functionImport, targetFunction)
        {
            EntityUtil.CheckArgumentNull(structuralTypeMappingsList, "structuralTypeMappingsList");
            EntityUtil.CheckArgumentNull(itemCollection, "itemCollection");
            Debug.Assert(!functionImport.IsComposableAttribute, "!functionImport.IsComposableAttribute");
            Debug.Assert(!targetFunction.IsComposableAttribute, "!targetFunction.IsComposableAttribute");

            if (structuralTypeMappingsList.Count == 0)
            {
                this.ResultMappings = new OM.ReadOnlyCollection<FunctionImportStructuralTypeMappingKB>(
                    new FunctionImportStructuralTypeMappingKB[] { 
                        new FunctionImportStructuralTypeMappingKB(new List<FunctionImportStructuralTypeMapping>(), itemCollection) });
                this.noExplicitResultMappings = true;
            }
            else
            {
                Debug.Assert(functionImport.ReturnParameters.Count == structuralTypeMappingsList.Count);
                this.ResultMappings = new OM.ReadOnlyCollection<FunctionImportStructuralTypeMappingKB>(
                    EntityUtil.CheckArgumentNull(structuralTypeMappingsList, "structuralTypeMappingsList")
                        .Select((structuralTypeMappings) => new FunctionImportStructuralTypeMappingKB(
                            EntityUtil.CheckArgumentNull(structuralTypeMappings, "structuralTypeMappings"),
                            itemCollection))
                        .ToArray());
                this.noExplicitResultMappings = false;
            }
        }
        public void Cannot_create_with_null_argument()
        {
            var entityType = new EntityType("ET", "N", DataSpace.CSpace);
            var entitySet = new EntitySet("ES", "S", "T", "Q", entityType);
            var function = new EdmFunction("F", "N", DataSpace.SSpace, new EdmFunctionPayload());
            var parameterBindings = Enumerable.Empty<ModificationFunctionParameterBinding>();
            var rowsAffectedParameter = new FunctionParameter("rows_affected", new TypeUsage(), ParameterMode.Out);
            var resultBindings = Enumerable.Empty<ModificationFunctionResultBinding>();

            Assert.Equal(
                "entitySet",
                Assert.Throws<ArgumentNullException>(
                    () => new ModificationFunctionMapping(
                        null, entityType, function, 
                        parameterBindings, rowsAffectedParameter, resultBindings)).ParamName);

            Assert.Equal(
                "function",
                Assert.Throws<ArgumentNullException>(
                    () => new ModificationFunctionMapping(
                        entitySet, entityType, null,
                        parameterBindings, rowsAffectedParameter, resultBindings)).ParamName);

            Assert.Equal(
                "parameterBindings",
                Assert.Throws<ArgumentNullException>(
                    () => new ModificationFunctionMapping(
                        entitySet, entityType, function,
                        null, rowsAffectedParameter, resultBindings)).ParamName);
        }
        internal FunctionImportMappingNonComposable(
            EdmFunction functionImport,
            EdmFunction targetFunction,
            List<List<FunctionImportStructuralTypeMapping>> structuralTypeMappingsList,
            ItemCollection itemCollection)
            : base(functionImport, targetFunction)
        {
            //Contract.Requires(structuralTypeMappingsList != null);
            //Contract.Requires(itemCollection != null);
            Debug.Assert(!functionImport.IsComposableAttribute, "!functionImport.IsComposableAttribute");
            Debug.Assert(!targetFunction.IsComposableAttribute, "!targetFunction.IsComposableAttribute");

            if (structuralTypeMappingsList.Count == 0)
            {
                ResultMappings = new OM.ReadOnlyCollection<FunctionImportStructuralTypeMappingKB>(
                    new[]
                        {
                            new FunctionImportStructuralTypeMappingKB(new List<FunctionImportStructuralTypeMapping>(), itemCollection)
                        });
                noExplicitResultMappings = true;
            }
            else
            {
                Debug.Assert(functionImport.ReturnParameters.Count == structuralTypeMappingsList.Count);
                ResultMappings = new OM.ReadOnlyCollection<FunctionImportStructuralTypeMappingKB>(
                    structuralTypeMappingsList
                        .Select(
                            (structuralTypeMappings) => new FunctionImportStructuralTypeMappingKB(
                                                            structuralTypeMappings,
                                                            itemCollection))
                        .ToArray());
                noExplicitResultMappings = false;
            }
        }
        /// <summary>
        /// Initializes a new ModificationFunctionMapping instance.
        /// </summary>
        /// <param name="entitySet">The entity or association set.</param>
        /// <param name="entityType">The entity or association type.</param>
        /// <param name="function">The metadata of function to which we should bind.</param>
        /// <param name="parameterBindings">Bindings for function parameters.</param>
        /// <param name="rowsAffectedParameter">The output parameter producing number of rows affected.</param>
        /// <param name="resultBindings">Bindings for the results of function evaluation</param>
        public ModificationFunctionMapping(
            EntitySetBase entitySet,
            EntityTypeBase entityType,
            EdmFunction function,
            IEnumerable<ModificationFunctionParameterBinding> parameterBindings,
            FunctionParameter rowsAffectedParameter,
            IEnumerable<ModificationFunctionResultBinding> resultBindings)
        {
            Check.NotNull(entitySet, "entitySet");
            Check.NotNull(function, "function");
            Check.NotNull(parameterBindings, "parameterBindings");

            _function = function;
            _rowsAffectedParameter = rowsAffectedParameter;

            _parameterBindings = new ReadOnlyCollection<ModificationFunctionParameterBinding>(parameterBindings.ToList());

            if (null != resultBindings)
            {
                var bindings = resultBindings.ToList();

                if (0 < bindings.Count)
                {
                    _resultBindings = new ReadOnlyCollection<ModificationFunctionResultBinding>(bindings);
                }
            }

            _collocatedAssociationSetEnds =
                new ReadOnlyCollection<AssociationSetEnd>(
                    GetReferencedAssociationSetEnds(entitySet as EntitySet, entityType as EntityType, parameterBindings)
                        .ToList());
        }
        public FunctionImportMappingComposable(
            EdmFunction functionImport,
            EdmFunction targetFunction,
            List<Tuple<StructuralType, List<StorageConditionPropertyMapping>, List<StoragePropertyMapping>>> structuralTypeMappings)
            : base(functionImport, targetFunction)
        {
            if (!functionImport.IsComposableAttribute)
            {
                throw new ArgumentException(Strings.NonComposableFunctionCannotBeMappedAsComposable("functionImport"));
            }

            if (!targetFunction.IsComposableAttribute)
            {
                throw new ArgumentException(Strings.NonComposableFunctionCannotBeMappedAsComposable("targetFunction"));
            }

            if (functionImport.EntitySet != null)
            {
                throw new NotSupportedException(Strings.ComposableFunctionImportsReturningEntitiesNotSupported);
            }

            EdmType resultType;
            if (!MetadataHelper.TryGetFunctionImportReturnType(functionImport, 0, out resultType))
            {
                throw new ArgumentException(Strings.InvalidReturnTypeForComposableFunction);
            }

            if (!TypeSemantics.IsScalarType(resultType)
                && (structuralTypeMappings == null || structuralTypeMappings.Count == 0))
            {
                throw new ArgumentException(Strings.StructuralTypeMappingsMustNotBeNullForFunctionImportsReturingNonScalarValues);
            }

            m_structuralTypeMappings = structuralTypeMappings;
        }
        public void Can_not_create_composable_function_import_mapping_with_entity_set_and_null_structural_type_mappings()
        {
            var entityType = new EntityType("E", "N", DataSpace.CSpace);
            var entitySet = new EntitySet("ES", null, null, null, entityType);

            var functionImport =
                new EdmFunction(
                    "f",
                    "entityModel",
                    DataSpace.CSpace,
                    new EdmFunctionPayload
                        {
                            IsComposable = true,
                            EntitySets = new[] { entitySet },
                            ReturnParameters =
                                new[]
                                    {
                                        new FunctionParameter(
                                            "ReturnType", 
                                            TypeUsage.CreateDefaultTypeUsage(entityType), 
                                            ParameterMode.ReturnValue)
                                    }
                        });

            Assert.Equal(
                Strings.ComposableFunctionImportsReturningEntitiesNotSupported,
                Assert.Throws<NotSupportedException>(
                    () => new FunctionImportMappingComposable(
                              functionImport,
                              new EdmFunction(
                              "f", "store", DataSpace.CSpace, new EdmFunctionPayload { IsComposable = true }),
                              null)).Message);
        }
        internal FunctionImportMappingComposable(
            EdmFunction functionImport,
            EdmFunction targetFunction,
            List<Tuple<StructuralType, List<StorageConditionPropertyMapping>, List<StoragePropertyMapping>>> structuralTypeMappings,
            EdmProperty[] targetFunctionKeys,
            StorageMappingItemCollection mappingItemCollection,
            string sourceLocation,
            LineInfo lineInfo) 
            : base(functionImport, targetFunction)
        {
            EntityUtil.CheckArgumentNull(mappingItemCollection, "mappingItemCollection");
            Debug.Assert(functionImport.IsComposableAttribute, "functionImport.IsComposableAttribute");
            Debug.Assert(targetFunction.IsComposableAttribute, "targetFunction.IsComposableAttribute");
            Debug.Assert(functionImport.EntitySet == null || structuralTypeMappings != null, "Function import returning entities must have structuralTypeMappings.");
            Debug.Assert(structuralTypeMappings == null || structuralTypeMappings.Count > 0, "Non-null structuralTypeMappings must not be empty.");
            EdmType resultType;
            Debug.Assert(
                structuralTypeMappings != null ||
                MetadataHelper.TryGetFunctionImportReturnType<EdmType>(functionImport, 0, out resultType) && TypeSemantics.IsScalarType(resultType),
                "Either type mappings should be specified or the function import should be Collection(Scalar).");
            Debug.Assert(functionImport.EntitySet == null || targetFunctionKeys != null, "Keys must be inferred for a function import returning entities.");
            Debug.Assert(targetFunctionKeys == null || targetFunctionKeys.Length > 0, "Keys must be null or non-empty.");

            m_mappingItemCollection = mappingItemCollection;
            // We will use these parameters to target s-space function calls in the generated command tree. 
            // Since enums don't exist in s-space we need to use the underlying type.
            m_commandParameters = functionImport.Parameters.Select(p => TypeHelpers.GetPrimitiveTypeUsageForScalar(p.TypeUsage).Parameter(p.Name)).ToArray();
            m_structuralTypeMappings = structuralTypeMappings;
            m_targetFunctionKeys = targetFunctionKeys;
            m_sourceLocation = sourceLocation;
            m_lineInfo = lineInfo;
        }
        internal FunctionImportMapping(EdmFunction functionImport, EdmFunction targetFunction)
        {
            DebugCheck.NotNull(functionImport);
            DebugCheck.NotNull(targetFunction);

            _functionImport = functionImport;
            _targetFunction = targetFunction;
        }
Example #18
0
        internal DbFunctionAggregate(TypeUsage resultType, DbExpressionList arguments, EdmFunction function, bool isDistinct)
            : base(resultType, arguments)
        {
            Debug.Assert(function != null, "DbFunctionAggregate.Function cannot be null");

            _aggregateFunction = function;
            _distinct = isDistinct;
        }
        internal FunctionImportMapping(EdmFunction functionImport, EdmFunction targetFunction)
        {
            Contract.Requires(functionImport != null);
            Contract.Requires(targetFunction != null);

            FunctionImport = functionImport;
            TargetFunction = targetFunction;
        }
        internal DbFunctionAggregate(TypeUsage resultType, DbExpressionList arguments, EdmFunction function, bool isDistinct)
            : base(resultType, arguments)
        {
            DebugCheck.NotNull(function);

            _aggregateFunction = function;
            _distinct = isDistinct;
        }
        internal FunctionImportMapping(EdmFunction functionImport, EdmFunction targetFunction)
        {
            Check.NotNull(functionImport, "functionImport");
            Check.NotNull(targetFunction, "targetFunction");

            FunctionImport = functionImport;
            TargetFunction = targetFunction;
        }
        /// <summary>
        /// Gets the accessibility that should be applied to a method being generated from the provided EdmFunction.
        ///
        /// defaults to public if no annotation is found.
        /// </summary>
        public static string ForMethod(EdmFunction function)
        {
            if (function == null)
            {
                return null;
            }

            return GetAccessibility(function, METHOD_ACCESS);
        }
        public void Can_get_and_set_schema()
        {
            var function
                = new EdmFunction("F", "N", DataSpace.SSpace)
                      {
                          Schema = "Foo"
                      };

            Assert.Equal("Foo", function.Schema);
        }
        public void Can_get_full_name()
        {
            var function = new EdmFunction("F", "N", DataSpace.SSpace);

            Assert.Equal("N.F", function.FullName);

            function.Name = "Foo";

            Assert.Equal("N.Foo", function.FullName);
        }
        public void Can_get_function_import_and_store_function()
        {
            var functionImport = 
                new EdmFunction("f", "entityModel", DataSpace.CSpace);
            var storeFunction =
                new EdmFunction("f", "storeModel", DataSpace.SSpace);

            var functionImporMapping = new FunctionImportMappingFake(functionImport, storeFunction);

            Assert.Same(functionImport, functionImporMapping.FunctionImport);
            Assert.Same(storeFunction, functionImporMapping.TargetFunction);
        }
        /// <summary>
        /// Initializes a new FunctionImportMappingNonComposable instance.
        /// </summary>
        /// <param name="functionImport">The model function import.</param>
        /// <param name="targetFunction">The store non-composable function.</param>
        /// <param name="resultMappings">The function import result mappings.</param>
        /// <param name="containerMapping">The parent container mapping.</param>
        public FunctionImportMappingNonComposable(
            EdmFunction functionImport,
            EdmFunction targetFunction,
            IEnumerable<FunctionImportResultMapping> resultMappings,
            EntityContainerMapping containerMapping)
            : base(
                Check.NotNull(functionImport, "functionImport"),
                Check.NotNull(targetFunction, "targetFunction"))
        {
            Check.NotNull(resultMappings, "resultMappings");
            Check.NotNull(containerMapping, "containerMapping");

            Debug.Assert(!functionImport.IsComposableAttribute);
            Debug.Assert(!targetFunction.IsComposableAttribute);

 
            if (!resultMappings.Any())
            {
                // when this method is invoked when a CodeFirst model is being built (e.g. from a custom convention) the
                // StorageMappingItemCollection will be null. In this case we can provide an empty EdmItemCollection which
                // will allow inferring implicit result mapping
                var edmItemCollection = containerMapping.StorageMappingItemCollection != null
                    ? containerMapping.StorageMappingItemCollection.EdmItemCollection
                    : new EdmItemCollection(new EdmModel(DataSpace.CSpace));

                _internalResultMappings = new ReadOnlyCollection<FunctionImportStructuralTypeMappingKB>(
                    new[]
                        {
                            new FunctionImportStructuralTypeMappingKB(
                                new List<FunctionImportStructuralTypeMapping>(), 
                                edmItemCollection)
                        });
                noExplicitResultMappings = true;
            }
            else
            {
                Debug.Assert(functionImport.ReturnParameters.Count == resultMappings.Count());

                _internalResultMappings = new ReadOnlyCollection<FunctionImportStructuralTypeMappingKB>(
                    resultMappings
                        .Select(
                            resultMapping => new FunctionImportStructuralTypeMappingKB(
                                                    resultMapping.TypeMappings,
                                                    containerMapping.StorageMappingItemCollection.EdmItemCollection))
                        .ToArray());

                noExplicitResultMappings = false;
            }

            _resultMappings = new ReadOnlyCollection<FunctionImportResultMapping>(resultMappings.ToList());
        }
        public static EdmFunction AddFunction(this EdmModel database, string name, EdmFunctionPayload functionPayload)
        {
            DebugCheck.NotNull(database);
            DebugCheck.NotEmpty(name);

            var uniqueIdentifier = database.Functions.UniquifyName(name);

            var function
                = new EdmFunction(
                    uniqueIdentifier,
                    DefaultStoreNamespace,
                    DataSpace.SSpace,
                    functionPayload);

            database.AddItem(function);

            return function;
        }
Example #28
0
        public void VisitEdmModel_should_visit_edm_functions()
        {
            var visitorMock
                = new Mock<EdmModelVisitor>
                      {
                          CallBase = true
                      };

            var function = new EdmFunction("F", "N", DataSpace.SSpace);
            var model = new EdmModel(DataSpace.SSpace);
            model.AddItem(function);

            visitorMock.Object.VisitEdmModel(model);

            visitorMock.Verify(v => v.VisitFunctions(It.IsAny<IEnumerable<EdmFunction>>()), Times.Once());
            visitorMock.Verify(v => v.VisitMetadataItem(function), Times.Once());
            visitorMock.Verify(v => v.VisitEdmFunction(function), Times.Once());
        }
Example #29
0
 // <summary>
 // Returns the function import in the target space, for the given entity container.
 // </summary>
 internal virtual bool TryGetFunctionImport(
     EntityContainer entityContainer, String functionImportName, bool ignoreCase, out EdmFunction functionImport)
 {
     // There are no entity containers in the OSpace. So there is no mapping involved.
     // Hence the name should be a valid name in the CSpace.
     functionImport = null;
     if (ignoreCase)
     {
         functionImport =
             entityContainer.FunctionImports.Where(
                 fi => String.Equals(fi.Name, functionImportName, StringComparison.OrdinalIgnoreCase)).SingleOrDefault();
     }
     else
     {
         functionImport = entityContainer.FunctionImports.Where(fi => fi.Name == functionImportName).SingleOrDefault();
     }
     return functionImport != null;
 }
        public void WriteFunctionElementHeader_should_write_element_and_attributes()
        {
            var fixture = new Fixture();

            var function = new EdmFunction(
                "Foo",
                "Bar",
                DataSpace.SSpace,
                new EdmFunctionPayload
                    {
                        Schema = "dbo"
                    });

            fixture.Writer.WriteFunctionElementHeader(function);

            Assert.Equal(
                "<Function Name=\"Foo\" Aggregate=\"false\" BuiltIn=\"false\" NiladicFunction=\"false\" IsComposable=\"true\" ParameterTypeSemantics=\"AllowImplicitConversion\" Schema=\"dbo\"",
                fixture.ToString());
        }
        public void GetTemplatesFunctionImportSegmentTemplate_ReturnsTemplates_ForEmptyParameter()
        {
            // Arrange
            EdmFunction                   function              = new EdmFunction("NS", "MyFunctionImport", IntPrimitive, false, null, false);
            EdmEntityContainer            container             = new EdmEntityContainer("NS", "Default");
            EdmFunctionImport             functionImport        = new EdmFunctionImport(container, "MyFunctionImport", function);
            FunctionImportSegmentTemplate functionImportSegment = new FunctionImportSegmentTemplate(functionImport, null);

            // Act & Assert
            IEnumerable <string> templates = functionImportSegment.GetTemplates();
            string template = Assert.Single(templates);

            Assert.Equal("/MyFunctionImport()", template);

            // Act & Assert
            templates = functionImportSegment.GetTemplates(new ODataRouteOptions
            {
                EnableNonParenthsisForEmptyParameterFunction = true
            });
            template = Assert.Single(templates);
            Assert.Equal("/MyFunctionImport", template);
        }
Example #32
0
        /// <summary>
        /// Initializes a new <see cref="IEdmOperationImport"/> instance.
        /// </summary>
        /// <param name="name">name of the service operation.</param>
        /// <param name="function">Function imported in.</param>
        /// <param name="resultSet">EntitySet of the result expected from this operation.</param>
        public EdmFunctionImport AddFunctionAndFunctionImport(string name, IEdmTypeReference bindingType, IEdmTypeReference resultType, IEdmEntitySet resultSet, bool isBindable)
        {
            var edmFunction = new EdmFunction(this.Namespace, name, resultType, isBindable, null, false /*isComposable*/);

            if (isBindable)
            {
                edmFunction.AddParameter("bindingparameter", bindingType);
            }

            IEdmPathExpression entitySetExpression = null;

            if (resultSet != null)
            {
                entitySetExpression = new EdmPathExpression(resultSet.Name);
            }

            this.AddOperation(edmFunction);
            var functionImport = new EdmFunctionImport(this, name, edmFunction, entitySetExpression, false);

            this.AddOperationImport(name, functionImport);
            return(functionImport);
        }
Example #33
0
        private static bool ProcessIsNullOverAnything(
            RuleProcessingContext context,
            System.Data.Entity.Core.Query.InternalTrees.Node isNullNode,
            out System.Data.Entity.Core.Query.InternalTrees.Node newNode)
        {
            Command command = context.Command;

            switch (isNullNode.Child0.Op.OpType)
            {
            case OpType.Cast:
                newNode = command.CreateNode((Op)command.CreateConditionalOp(OpType.IsNull), isNullNode.Child0.Child0);
                break;

            case OpType.Function:
                EdmFunction function = ((FunctionOp)isNullNode.Child0.Op).Function;
                newNode = ScalarOpRules.PreservesNulls(function) ? command.CreateNode((Op)command.CreateConditionalOp(OpType.IsNull), isNullNode.Child0.Child0) : isNullNode;
                break;

            default:
                newNode = isNullNode;
                break;
            }
            switch (isNullNode.Child0.Op.OpType)
            {
            case OpType.Constant:
            case OpType.InternalConstant:
            case OpType.NullSentinel:
                return(ScalarOpRules.ProcessIsNullOverConstant(context, newNode, out newNode));

            case OpType.Null:
                return(ScalarOpRules.ProcessIsNullOverNull(context, newNode, out newNode));

            case OpType.VarRef:
                return(ScalarOpRules.ProcessIsNullOverVarRef(context, newNode, out newNode));

            default:
                return(!object.ReferenceEquals((object)isNullNode, (object)newNode));
            }
        }
Example #34
0
        public void Ctor_InitializeParameterMappingsProperty_Function()
        {
            // Arrange
            IEdmModel          model      = new Mock <IEdmModel>().Object;
            IEdmEntityType     returnType = new Mock <IEdmEntityType>().Object;
            EdmEntityContainer container  = new EdmEntityContainer("NS", "Container");
            EdmFunction        function   = new EdmFunction("NS", "Function",
                                                            new EdmEntityTypeReference(returnType, isNullable: false));

            Dictionary <string, string> parameterMappings = new Dictionary <string, string>()
            {
                { "Parameter1", "{param1}" },
                { "Parameter2", "{param2}" }
            };

            // Act
            var template = new BoundFunctionPathSegmentTemplate(
                new BoundFunctionPathSegment(function, model, parameterMappings));

            // Assert
            Assert.Equal(2, template.ParameterMappings.Count);
        }
Example #35
0
            public void Apply(EntityContainer item, DbModel model)
            {
                var customFuncStore = EdmFunction.Create("MyCustomFunc", "SqlServer", DataSpace.SSpace, new EdmFunctionPayload
                {
                    ParameterTypeSemantics = ParameterTypeSemantics.AllowImplicitConversion,
                    IsComposable           = true,
                    IsAggregate            = false,
                    StoreFunctionName      = "MyCustomFunc",
                    IsBuiltIn        = false,
                    ReturnParameters = new[]
                    {
                        FunctionParameter.Create("ReturnType", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Int32), ParameterMode.ReturnValue)
                    },
                    Parameters = new[]
                    {
                        FunctionParameter.Create("input", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String), ParameterMode.In),
                    }
                }, null);


                model.StoreModel.AddItem(customFuncStore);
            }
Example #36
0
        public static EdmFunction CreateFunction([NotNull] this EdmModel item,
                                                 string name,
                                                 IList <FunctionParameter> parameters,
                                                 IList <FunctionParameter> returnValues,
                                                 string body = null)
        {
            if (item == null)
            {
                throw new ArgumentNullException(nameof(item));
            }
            var payload = new EdmFunctionPayload
            {
                StoreFunctionName = name,
                Parameters        = parameters,
                ReturnParameters  = returnValues,
                Schema            = item.GetDefaultSchema(),
            };

            var function = EdmFunction.Create(name, item.GetDefaultNamespace(), item.DataSpace, payload, null);

            return(function);
        }
Example #37
0
        public void TryMatch_ReturnTrue_IfSameFunction()
        {
            // Arrange
            IEdmModel      model      = new Mock <IEdmModel>().Object;
            IEdmEntityType returnType = new Mock <IEdmEntityType>().Object;
            EdmFunction    function   = new EdmFunction("NS", "Function", new EdmEntityTypeReference(returnType, isNullable: false));

            function.AddParameter("Parameter1", EdmCoreModel.Instance.GetInt32(isNullable: false));
            function.AddParameter("Parameter2", EdmCoreModel.Instance.GetInt32(isNullable: false));

            Dictionary <string, string> parameterValues = new Dictionary <string, string>()
            {
                { "Parameter1", "1" },
                { "Parameter2", "2" }
            };

            Dictionary <string, string> parameterMappings = new Dictionary <string, string>()
            {
                { "Parameter1", "{param1}" },
                { "Parameter2", "{param2}" }
            };

            BoundFunctionPathSegment         segment  = new BoundFunctionPathSegment(function, model, parameterValues: parameterValues);
            BoundFunctionPathSegmentTemplate template = new BoundFunctionPathSegmentTemplate(
                new BoundFunctionPathSegment(function, model, parameterValues: parameterMappings));

            // Act
            Dictionary <string, object> values = new Dictionary <string, object>();
            bool result = template.TryMatch(segment, values);

            // Assert
            Assert.True(result);
            Assert.Equal(4, values.Count);
            Assert.Equal("1", values["param1"]);
            Assert.Equal("2", values["param2"]);

            Assert.Equal(1, (values[ODataParameterValue.ParameterValuePrefix + "param1"] as ODataParameterValue).Value);
            Assert.Equal(2, (values[ODataParameterValue.ParameterValuePrefix + "param2"] as ODataParameterValue).Value);
        }
        public void VerifyAndBuildParameterMappings_ThrowsODataException_MissMatchParameters()
        {
            // Arrange
            IEdmTypeReference strType  = EdmCoreModel.Instance.GetString(false);
            EdmFunction       function = new EdmFunction("NS", "Function", strType);

            function.AddParameter("Name", strType);

            // Act & Assert
            IDictionary <string, string> parameters = new Dictionary <string, string>
            {
                { "Other", "{Other}" }
            };
            Action test = () => function.VerifyAndBuildParameterMappings(parameters);

            ExceptionAssert.Throws <ODataException>(test, "Missing the required parameter 'Name' is in the operation 'NS.Function' parameter mapping.");

            // Act & Assert
            parameters["Name"] = "{Name}"; // Other is still in the dictionary
            test = () => function.VerifyAndBuildParameterMappings(parameters);
            ExceptionAssert.Throws <ODataException>(test, "Cannot find parameter 'Other' is in the operation 'NS.Function'.");
        }
        public void MatchForFunction_ReturnsBuiltParameters_ParameterAlias()
        {
            // Arrange
            var         strType  = EdmCoreModel.Instance.GetString(false);
            EdmModel    model    = new EdmModel();
            EdmFunction function = new EdmFunction("NS", "MyFunction", strType, true, null, false);

            function.AddParameter("name", strType);
            model.AddElement(function);

            RouteValueDictionary routeValues = new RouteValueDictionary()
            {
                { "nameValue", "@p" }
            };

            HttpContext httpContext = new DefaultHttpContext();

            httpContext.Request.QueryString = new QueryString("?@p='abc'");
            ODataTemplateTranslateContext context = new ODataTemplateTranslateContext
            {
                HttpContext = httpContext,
                RouteValues = routeValues,
                Model       = model
            };

            IDictionary <string, string> parameterMappings = new Dictionary <string, string>
            {
                { "name", "nameValue" }
            };

            // Act
            IList <OperationSegmentParameter> parameters = SegmentTemplateHelpers.Match(context, function, parameterMappings);

            // Assert
            OperationSegmentParameter functionParameter = Assert.Single(parameters);

            Assert.Equal("name", functionParameter.Name);
            Assert.Equal("abc", functionParameter.Value);
        }
Example #40
0
        public EdmFunction Create(FunctionDescriptor functionDescriptor)
        {
            Debug.Assert(functionDescriptor != null, "functionDescriptor is null");

            if (_schema == null && functionDescriptor.DatabaseSchema == null)
            {
                throw new InvalidOperationException(
                          string.Format(
                              "Database schema is not defined for function '{0}'. Either set a default database schema or use the DbFunctionEx attribute with non-null DatabaseSchema value.",
                              functionDescriptor.Name));
            }

            var functionPayload =
                new EdmFunctionPayload
            {
                Parameters = functionDescriptor
                             .Parameters
                             .Select(
                    p => FunctionParameter.Create(
                        p.Name,
                        GetStorePrimitiveType(p),
                        p.IsOutParam
                                    ? ParameterMode.InOut
                                    : ParameterMode.In)).ToArray(),

                ReturnParameters = CreateFunctionReturnParameters(functionDescriptor),
                IsComposable     = functionDescriptor.StoreFunctionKind != StoreFunctionKind.StoredProcedure,
                Schema           = functionDescriptor.DatabaseSchema ?? _schema,
                IsBuiltIn        = functionDescriptor.IsBuiltIn,
                IsNiladic        = functionDescriptor.IsNiladic
            };

            return(EdmFunction.Create(
                       functionDescriptor.Name,
                       _namespace,
                       DataSpace.SSpace,
                       functionPayload,
                       null));
        }
Example #41
0
        private EdmFunction BuildFunction(OeOperationConfiguration operationConfiguration, Dictionary <Type, EntityTypeInfo> entityTypeInfos)
        {
            IEdmTypeReference edmTypeReference;
            Type itemType = Parsers.OeExpressionHelper.GetCollectionItemType(operationConfiguration.ReturnType);

            if (itemType == null)
            {
                edmTypeReference = GetEdmTypeReference(operationConfiguration.ReturnType, entityTypeInfos);
                if (edmTypeReference == null)
                {
                    return(null);
                }
            }
            else
            {
                edmTypeReference = GetEdmTypeReference(itemType, entityTypeInfos);
                if (edmTypeReference == null)
                {
                    return(null);
                }

                edmTypeReference = new EdmCollectionTypeReference(new EdmCollectionType(edmTypeReference));
            }

            var edmFunction = new EdmFunction(operationConfiguration.NamespaceName, operationConfiguration.MethodInfoName, edmTypeReference);

            foreach (OeOperationParameterConfiguration parameterConfiguration in operationConfiguration.Parameters)
            {
                edmTypeReference = GetEdmTypeReference(parameterConfiguration.ClrType, entityTypeInfos);
                if (edmTypeReference == null)
                {
                    return(null);
                }

                edmFunction.AddParameter(parameterConfiguration.Name, edmTypeReference);
            }

            return(edmFunction);
        }
Example #42
0
        private EdmFunction BuildFunction(OeOperationConfiguration functionConfiguration)
        {
            IEdmTypeReference edmTypeReference;
            Type itemType = Parsers.OeExpressionHelper.GetCollectionItemType(functionConfiguration.ReturnType);

            if (itemType == null)
            {
                edmTypeReference = GetEdmTypeReference(functionConfiguration.ReturnType);
                if (edmTypeReference == null)
                {
                    return(null);
                }
            }
            else
            {
                edmTypeReference = GetEdmTypeReference(itemType);
                if (edmTypeReference == null)
                {
                    return(null);
                }

                edmTypeReference = new EdmCollectionTypeReference(new EdmCollectionType(edmTypeReference));
            }

            var edmFunction = new EdmFunction(functionConfiguration.NamespaceName ?? "", functionConfiguration.Name, edmTypeReference);

            foreach (OeFunctionParameterConfiguration parameterConfiguration in functionConfiguration.Parameters)
            {
                edmTypeReference = GetEdmTypeReference(parameterConfiguration.ClrType);
                if (edmTypeReference == null)
                {
                    return(null);
                }

                edmFunction.AddParameter(parameterConfiguration.Name, edmTypeReference);
            }

            return(edmFunction);
        }
Example #43
0
        private static int SelectDateTimeMethod(EdmFunction function, Expression[] args)
        {
            Type firstArg = TypeHelper.MakeNotNullable(args[0].Type);

            if (firstArg == typeof(DateTime))
            {
                return(0);
            }
            else if (firstArg == typeof(DateTimeOffset))
            {
                return(1);
            }
            else if (firstArg == typeof(TimeSpan))
            {
                return(2);
            }

            throw new NotSupportedException(
                      string.Format("Type '{2}' is not supported for '{0}' date function ",
                                    function.FullName,
                                    firstArg.Name));
        }
        private static EdmFunction CreateFullTextEdmFunction(MethodInfo method, DbFunctionAttribute dbFunctionInfo)
        {
            if (method == null)
            {
                throw new ArgumentNullException("method");
            }
            if (dbFunctionInfo == null)
            {
                throw new ArgumentNullException("dbFunctionInfo");
            }

            return(EdmFunction.Create(
                       dbFunctionInfo.FunctionName,
                       dbFunctionInfo.NamespaceName,
                       DataSpace.SSpace,
                       new EdmFunctionPayload
            {
                ParameterTypeSemantics = ParameterTypeSemantics.AllowImplicitConversion,
                Schema = string.Empty,
                IsBuiltIn = true,
                IsAggregate = false,
                IsFromProviderManifest = true,
                StoreFunctionName = dbFunctionInfo.FunctionName,
                IsComposable = true,
                ReturnParameters = new[]
                {
                    FunctionParameter.Create(
                        "ReturnType",
                        MapTypeToEdmType(method.ReturnType),
                        ParameterMode.ReturnValue)
                },
                Parameters = method.GetParameters().Select(
                    x => FunctionParameter.Create(
                        x.Name,
                        MapTypeToEdmType(x.ParameterType),
                        ParameterMode.In)).ToList()
            },
                       new List <MetadataProperty>()));
        }
        public ODataMissingOperationGeneratorTests()
        {
            this.model               = new EdmModel();
            this.container           = new EdmEntityContainer("Fake", "Container");
            this.functionEdmMetadata = new EdmFunction("Fake", "FakeFunction", EdmCoreModel.Instance.GetInt32(false), true /*isBound*/, null, true /*isComposable*/);
            this.actionEdmMetadata   = new EdmAction("Fake", "FakeAction", EdmCoreModel.Instance.GetInt32(false), true /*isBound*/, null /*entitySetPath*/);
            this.model.AddElement(this.container);
            this.model.AddElement(this.actionEdmMetadata);
            this.model.AddElement(this.functionEdmMetadata);

            this.allOperations = new EdmOperation[] { this.actionEdmMetadata, this.functionEdmMetadata };

            this.odataAction = new ODataAction {
                Metadata = new Uri("http://temp.org/$metadata#Fake.FakeAction")
            };
            this.odataFunction = new ODataFunction {
                Metadata = new Uri("http://temp.org/$metadata#Fake.FakeFunction")
            };

            this.entry      = ReaderUtils.CreateNewResource();
            this.entityType = new EdmEntityType("TestNamespace", "EntityType");
        }
Example #46
0
        public void SetOperationLinkBuilder_ResetOperationLinkBuilder()
        {
            // Arrange
            IEdmModel         model      = new EdmModel();
            IEdmTypeReference returnType = EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.Boolean, isNullable: false);
            IEdmFunction      function   = new EdmFunction("NS", "Function", returnType, isBound: true, entitySetPathExpression: null, isComposable: false);

            // Act
            OperationLinkBuilder linkBuilder1 = new OperationLinkBuilder((ResourceContext a) => new Uri("http://localhost1"), followsConventions: false);

            model.SetOperationLinkBuilder(function, linkBuilder1);

            OperationLinkBuilder linkBuilder2 = new OperationLinkBuilder((ResourceContext a) => new Uri("http://localhost2"), followsConventions: false);

            model.SetOperationLinkBuilder(function, linkBuilder2);

            // Assert
            OperationLinkBuilder actualLinkBuilder = model.GetAnnotationValue <OperationLinkBuilder>(function);

            Assert.Same(linkBuilder2, actualLinkBuilder);
            Assert.Equal(new Uri("http://localhost2"), actualLinkBuilder.BuildLink((ResourceContext)null));
        }
        public void GetTemplatesWorksForPathWithTypeCastAndFunction()
        {
            // Arrange
            EdmEntityType customer = new EdmEntityType("NS", "Customer");

            customer.AddKeys(customer.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32));

            // VipCustomer
            EdmEntityType vipCustomer = new EdmEntityType("NS", "VipCustomer", customer);

            EdmEntityContainer container = new EdmEntityContainer("NS", "Default");
            var entitySet = container.AddEntitySet("Customers", customer);

            // function with optional parameters
            EdmFunction getSalaray = new EdmFunction("NS", "GetWholeSalary", IntType, isBound: true, entitySetPathExpression: null, isComposable: false);

            getSalaray.AddParameter("entityset", new EdmEntityTypeReference(vipCustomer, false));
            getSalaray.AddParameter("salary", IntType);
            getSalaray.AddOptionalParameter("minSalary", IntType);
            getSalaray.AddOptionalParameter("maxSalary", IntType, "129");

            ODataPathTemplate template = new ODataPathTemplate(
                new EntitySetSegmentTemplate(entitySet),
                KeySegmentTemplate.CreateKeySegment(customer, entitySet),
                new CastSegmentTemplate(vipCustomer, customer, entitySet),
                new FunctionSegmentTemplate(getSalaray, null));

            // Act
            IEnumerable <string> actual = template.GetTemplates();

            Assert.Equal(4, actual.Count());
            Assert.Equal(new[]
            {
                "Customers({key})/NS.VipCustomer/NS.GetWholeSalary(salary={salary},minSalary={minSalary},maxSalary={maxSalary})",
                "Customers({key})/NS.VipCustomer/GetWholeSalary(salary={salary},minSalary={minSalary},maxSalary={maxSalary})",
                "Customers/{key}/NS.VipCustomer/NS.GetWholeSalary(salary={salary},minSalary={minSalary},maxSalary={maxSalary})",
                "Customers/{key}/NS.VipCustomer/GetWholeSalary(salary={salary},minSalary={minSalary},maxSalary={maxSalary})",
            }, actual);
        }
Example #48
0
        static ODataEntryMetadataContextTest()
        {
            ActualEntityType = new EdmEntityType("ns", "TypeName");
            ActualEntityType.AddKeys(new IEdmStructuralProperty[] { ActualEntityType.AddStructuralProperty("ID2", EdmPrimitiveTypeKind.Int32), ActualEntityType.AddStructuralProperty("ID3", EdmPrimitiveTypeKind.Int32) });
            ActualEntityType.AddStructuralProperty("Name2", EdmCoreModel.Instance.GetString(isNullable: true), /*defaultValue*/ null);
            ActualEntityType.AddStructuralProperty("Name3", EdmCoreModel.Instance.GetString(isNullable: true), /*defaultValue*/ null);
            ActualEntityType.AddStructuralProperty("StreamProp1", EdmPrimitiveTypeKind.Stream);
            ActualEntityType.AddStructuralProperty("StreamProp2", EdmPrimitiveTypeKind.Stream);

            var navProp1 = ActualEntityType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo()
            {
                Target             = ActualEntityType,
                TargetMultiplicity = EdmMultiplicity.Many,
                Name = "NavProp1"
            });

            var navProp2 = ActualEntityType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo()
            {
                Target             = ActualEntityType,
                TargetMultiplicity = EdmMultiplicity.ZeroOrOne,
                Name = "NavProp2"
            });

            var          container = new EdmEntityContainer("Namespace", "Container");
            EdmEntitySet entitySet = container.AddEntitySet("EntitySet", ActualEntityType);

            entitySet.AddNavigationTarget(navProp1, entitySet);
            entitySet.AddNavigationTarget(navProp2, entitySet);

            Action1         = new EdmAction("Namespace", "Action1", null, true /*isBound*/, null /*entitySetPath*/);
            Action2         = new EdmAction("Namespace", "Action2", null, true /*isBound*/, null /*entitySetPath*/);
            ActionImport1   = new EdmActionImport(container, "ActionImport1", Action1);
            ActionImport2   = new EdmActionImport(container, "ActionImport2", Action2);
            Function1       = new EdmFunction("Namespace", "Function1", EdmCoreModel.Instance.GetString(isNullable: true), true /*isBound*/, null /*entitySetPath*/, true /*isComposable*/);
            Function2       = new EdmFunction("Namespace", "Function2", EdmCoreModel.Instance.GetString(isNullable: true), true /*isBound*/, null /*entitySetPath*/, true /*isComposable*/);
            FunctionImport1 = new EdmFunctionImport(container, "FunctionImport1", Function1);
            FunctionImport2 = new EdmFunctionImport(container, "FunctionImport2", Function2);
        }
Example #49
0
 void IStoreModelConvention <EntityContainer> .Apply(EntityContainer container, DbModel model)
 {
     foreach (MethodInfo mi in _containerType.GetMethods().Where(mi => mi.IsDefined(typeof(DbFunctionAttribute))))
     {
         FunctionDescriptor descriptor    = BuildFunctionDescriptor(mi);
         EdmFunction        storeFunction = CreateStoreFunction(model, descriptor);
         model.StoreModel.AddItem(storeFunction);
         if (descriptor.IsTableValued)
         {
             EdmFunction functionImport = CreateFunctionImport(model, descriptor);
             model.ConceptualModel.Container.AddFunctionImport(functionImport);
             if (functionImport.IsComposableAttribute)
             {
                 FunctionImportResultMapping resultMapping = new FunctionImportResultMapping();
                 if (functionImport.ReturnParameter.TypeUsage.EdmType.BuiltInTypeKind == BuiltInTypeKind.CollectionType)
                 {
                     EdmType itemType = ((CollectionType)functionImport.ReturnParameter.TypeUsage.EdmType).TypeUsage.EdmType;
                     RowType rowType  = (RowType)((CollectionType)storeFunction.ReturnParameter.TypeUsage.EdmType).TypeUsage.EdmType;
                     if (itemType.BuiltInTypeKind == BuiltInTypeKind.ComplexType)
                     {
                         ComplexType complexType = (ComplexType)itemType;
                         resultMapping.AddTypeMapping(new FunctionImportComplexTypeMapping(complexType, new Collection <FunctionImportReturnTypePropertyMapping>(
                                                                                               complexType.Properties.Select(p =>
                         {
                             var columnAttr = ((IEnumerable)p.MetadataProperties["ClrAttributes"].Value).OfType <ColumnAttribute>().SingleOrDefault();
                             return(new FunctionImportReturnTypeScalarPropertyMapping(p.Name, columnAttr != null && !string.IsNullOrEmpty(columnAttr.Name) ? columnAttr.Name : p.Name));
                         }).ToArray())));
                     }
                 }
                 model.ConceptualToStoreMapping.AddFunctionImportMapping((FunctionImportMapping) new FunctionImportMappingComposable(functionImport, storeFunction, resultMapping, model.ConceptualToStoreMapping));
             }
             else
             {
                 model.ConceptualToStoreMapping.AddFunctionImportMapping((FunctionImportMapping) new FunctionImportMappingNonComposable(functionImport, storeFunction, new FunctionImportResultMapping[0], model.ConceptualToStoreMapping));
             }
         }
     }
 }
        private static void AddModelDefinedFunction(DbModel model, MethodInfo methodInfo, ModelDefinedFunctionAttribute functionAttribute)
        {
            /*
            <!-- CSDL content -->
            <edmx:ConceptualModels>
                <Schema Namespace="AdventureWorks" Alias="Self" annotation:UseStrongSpatialTypes="false" xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation" xmlns:customannotation="http://schemas.microsoft.com/ado/2013/11/edm/customannotation" xmlns="http://schemas.microsoft.com/ado/2009/11/edm">
                    <Function Name="FormatName" ReturnType="Edm.String>
                        <Parameter Name="person" Type="AdventureWorks.Person" />
                        <DefiningExpression>
                            CASE WHEN person.Title IS NOT NULL THEN person.Title + ' ' ELSE '' END + person.FirstName + ' ' + person.LastName
                        </DefiningExpression>
                    </Function>
                </Schema>
            </edmx:ConceptualModels>
            */
            // Build above <ConceptualModels> imperatively.

            string modelNamespaceName = model.ConceptualModel.EntityTypes.Select(e => e.NamespaceName).FirstOrDefault();
            if (functionAttribute.NamespaceName != modelNamespaceName)
            {
                throw new InvalidOperationException($"The ModelDefinedFunctionAttribute for method {methodInfo.Name} must have namespaceName set to '{modelNamespaceName}'.");
            }

            EdmFunction modelFunction = EdmFunction.Create(
                methodInfo.Name,
                modelNamespaceName,
                DataSpace.CSpace, // <edmx:ConceptualModels>
                new EdmFunctionPayload
                {
                    IsComposable = true,
                    Parameters = model.GetModelParametersForModelDefinedFunction(methodInfo),
                    ReturnParameters = model.GetModelReturnParameters(methodInfo, functionAttribute),
                    EntitySets = model.GetModelEntitySets(methodInfo, functionAttribute),
                    CommandText = functionAttribute.EntitySql,
                },
                null);
            model.ConceptualModel.AddItem(modelFunction);
        }
        public void Can_retrieve_properties()
        {
            var entityType      = new EntityType("ET", "N", DataSpace.CSpace);
            var entitySet       = new EntitySet("ES", "S", "T", "Q", entityType);
            var entityContainer = new EntityContainer("EC", DataSpace.SSpace);

            entityContainer.AddEntitySetBase(entitySet);

            var function = new EdmFunction("F", "N", DataSpace.SSpace, new EdmFunctionPayload());
            var parameterBindings
                = new[]
                {
                new ModificationFunctionParameterBinding(
                    new FunctionParameter(),
                    new ModificationFunctionMemberPath(Enumerable.Empty <EdmMember>(), null),
                    true)
                };
            var rowsAffectedParameter = new FunctionParameter("rows_affected", new TypeUsage(), ParameterMode.Out);

            var resultBindings
                = new[]
                {
                new ModificationFunctionResultBinding(
                    "C",
                    EdmProperty.CreatePrimitive(
                        "P", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String)))
                };

            var mapping
                = new ModificationFunctionMapping(
                      entitySet, entityType, function,
                      parameterBindings, rowsAffectedParameter, resultBindings);

            Assert.Same(rowsAffectedParameter, mapping.RowsAffectedParameter);
            Assert.Same(function, mapping.Function);
            Assert.Equal(parameterBindings, mapping.ParameterBindings);
            Assert.Equal(resultBindings, mapping.ResultBindings);
        }
Example #52
0
        public static IEdmModel MultipleSchemasWithDifferentNamespacesEdm()
        {
            var namespaces = new string[]
            {
                "FindMethodsTestModelBuilder.MultipleSchemasWithDifferentNamespaces.first",
                "FindMethodsTestModelBuilder.MultipleSchemasWithDifferentNamespaces.second"
            };

            var model = new EdmModel();

            foreach (var namespaceName in namespaces)
            {
                var entityType1 = new EdmEntityType(namespaceName, "validEntityType1");
                entityType1.AddKeys(entityType1.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32));
                var entityType2 = new EdmEntityType(namespaceName, "VALIDeNTITYtYPE2");
                entityType2.AddKeys(entityType2.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32));
                var entityType3 = new EdmEntityType(namespaceName, "VALIDeNTITYtYPE3");
                entityType3.AddKeys(entityType3.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32));

                entityType1.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo {
                    Name = "Mumble", Target = entityType2, TargetMultiplicity = EdmMultiplicity.Many
                });

                var complexType = new EdmComplexType(namespaceName, "ValidNameComplexType1");
                complexType.AddStructuralProperty("aPropertyOne", new EdmComplexTypeReference(complexType, false));
                model.AddElements(new IEdmSchemaElement[] { entityType1, entityType2, entityType3, complexType });

                var function1 = new EdmFunction(namespaceName, "ValidFunction1", EdmCoreModel.Instance.GetSingle(false));
                var function2 = new EdmFunction(namespaceName, "ValidFunction1", EdmCoreModel.Instance.GetSingle(false));
                function2.AddParameter("param1", new EdmEntityTypeReference(entityType1, false));
                var function3 = new EdmFunction(namespaceName, "ValidFunction1", EdmCoreModel.Instance.GetSingle(false));
                function3.AddParameter("param1", EdmCoreModel.Instance.GetSingle(false));

                model.AddElements(new IEdmSchemaElement[] { function1, function2, function3 });
            }

            return(model);
        }
Example #53
0
        public void WriteFunctionName(SqlBuilder result, EdmFunction function)
        {
            string storeFunctionName = MetadataHelpers.TryGetValueForMetadataProperty <string>(function, "StoreFunctionNameAttribute");

            if (string.IsNullOrEmpty(storeFunctionName))
            {
                storeFunctionName = function.Name;
            }

            // If the function is a builtin (i.e. the BuiltIn attribute has been
            // specified, both store and canonical functions have this attribute),
            // then the function name should not be quoted;
            // additionally, no namespace should be used.
            if (MetadataHelpers.IsCanonicalFunction(function))
            {
                result.Append(storeFunctionName.ToUpperInvariant());
            }
            else if (IsBuiltInStoreFunction(function))
            {
                result.Append(storeFunctionName);
            }
            else
            {
                string schema = MetadataHelpers.TryGetValueForMetadataProperty <string>(function, "Schema");

                // Should we actually support this?
                if (String.IsNullOrEmpty(schema))
                {
                    result.Append(QuoteIdentifier(function.NamespaceName));
                }
                else
                {
                    result.Append(QuoteIdentifier(schema));
                }
                result.Append(".");
                result.Append(QuoteIdentifier(storeFunctionName));
            }
        }
        public void Build_does_not_try_map_not_mapped_functions()
        {
            var rowTypeProperty = CreateStoreProperty("p1", "int");
            var storeFunction   = EdmFunction.Create(
                "f_s",
                "storeModel",
                DataSpace.SSpace,
                new EdmFunctionPayload
            {
                IsComposable     = true,
                IsFunctionImport = false,
                ReturnParameters =
                    new[]
                {
                    FunctionParameter.Create(
                        "ReturnType",
                        RowType.Create(new[] { rowTypeProperty }, null).GetCollectionType(),
                        ParameterMode.ReturnValue)
                }
            },
                null);

            var modelContainer = EntityContainer.Create("C_C", DataSpace.CSpace, new EntitySet[0], null, null);
            var storeContainer = EntityContainer.Create("C_S", DataSpace.SSpace, new EntitySet[0], null, null);

            var storeModel = EdmModel.CreateStoreModel(storeContainer, null, null);

            storeModel.AddItem(storeFunction);

            var mappingContext = new SimpleMappingContext(storeModel, true);

            mappingContext.AddMapping(storeContainer, modelContainer);

            var entityModel = DbDatabaseMappingBuilder.Build(mappingContext).ConceptualModel;

            Assert.NotNull(entityModel);
            Assert.Empty(entityModel.Containers.Single().FunctionImports);
        }
        public void TryTranslateFunctionImportSegmentTemplate_ReturnsODataFunctionImportSegment()
        {
            // Arrange
            EdmFunction        function       = new EdmFunction("NS", "MyFunctionImport", IntPrimitive, false, null, false);
            EdmEntityContainer container      = new EdmEntityContainer("NS", "Default");
            EdmFunctionImport  functionImport = new EdmFunctionImport(container, "MyFunctionImport", function);

            FunctionImportSegmentTemplate template = new FunctionImportSegmentTemplate(functionImport, null);
            ODataTemplateTranslateContext context  = new ODataTemplateTranslateContext
            {
                RouteValues = new RouteValueDictionary()
            };

            // Act
            bool ok = template.TryTranslate(context);

            // Assert
            Assert.True(ok);
            ODataPathSegment       actual = Assert.Single(context.Segments);
            OperationImportSegment functionImportSegment = Assert.IsType <OperationImportSegment>(actual);

            Assert.Same(function, functionImportSegment.OperationImports.First().Operation);
        }
Example #56
0
 internal bool TryCreateFunctionImportMappingComposableWithScalarResult(
     EdmFunction functionImport,
     EdmFunction cTypeTargetFunction,
     EdmFunction sTypeTargetFunction,
     EdmType scalarResultType,
     RowType cTypeTvfElementType,
     IXmlLineInfo lineInfo,
     out FunctionImportMappingComposable mapping)
 {
     mapping = (FunctionImportMappingComposable)null;
     if (cTypeTvfElementType.Properties.Count > 1)
     {
         FunctionImportMappingComposableHelper.AddToSchemaErrors(Strings.Mapping_FunctionImport_ScalarMappingToMulticolumnTVF((object)functionImport.Identity, (object)sTypeTargetFunction.Identity), MappingErrorCode.MappingFunctionImportScalarMappingToMulticolumnTVF, this.m_sourceLocation, lineInfo, (IList <EdmSchemaError>) this.m_parsingErrors);
         return(false);
     }
     if (!FunctionImportMappingComposableHelper.ValidateFunctionImportMappingResultTypeCompatibility(TypeUsage.Create(scalarResultType), cTypeTvfElementType.Properties[0].TypeUsage))
     {
         FunctionImportMappingComposableHelper.AddToSchemaErrors(Strings.Mapping_FunctionImport_ScalarMappingTypeMismatch((object)functionImport.ReturnParameter.TypeUsage.EdmType.FullName, (object)functionImport.Identity, (object)sTypeTargetFunction.ReturnParameter.TypeUsage.EdmType.FullName, (object)sTypeTargetFunction.Identity), MappingErrorCode.MappingFunctionImportScalarMappingTypeMismatch, this.m_sourceLocation, lineInfo, (IList <EdmSchemaError>) this.m_parsingErrors);
         return(false);
     }
     mapping = new FunctionImportMappingComposable(functionImport, cTypeTargetFunction, (List <Tuple <StructuralType, List <ConditionPropertyMapping>, List <PropertyMapping> > >)null, (EdmProperty[])null, this._entityContainerMapping);
     return(true);
 }
Example #57
0
        public void Translate_ReturnsODataFunctionImportSegment()
        {
            // Arrange
            EdmFunction        function       = new EdmFunction("NS", "MyFunctionImport", IntPrimitive, false, null, false);
            EdmEntityContainer container      = new EdmEntityContainer("NS", "Default");
            EdmFunctionImport  functionImport = new EdmFunctionImport(container, "MyFunctionImport", function);

            FunctionImportSegmentTemplate template = new FunctionImportSegmentTemplate(functionImport, null);

            Mock <HttpContext>            httpContext = new Mock <HttpContext>();
            Mock <IEdmModel>              edmModel    = new Mock <IEdmModel>();
            ODataTemplateTranslateContext context     = new ODataTemplateTranslateContext(httpContext.Object,
                                                                                          new RouteValueDictionary(), edmModel.Object);

            // Act
            ODataPathSegment actual = template.Translate(context);

            // Assert
            Assert.NotNull(actual);
            OperationImportSegment functionImportSegment = Assert.IsType <OperationImportSegment>(actual);

            Assert.Same(function, functionImportSegment.OperationImports.First().Operation);
        }
        /// <summary>
        /// Constructs a new DbFunctionCommandTree that uses the specified metadata workspace, data space and function metadata
        /// </summary>
        /// <param name="metadata">The metadata workspace that the command tree should use.</param>
        /// <param name="dataSpace">The logical 'space' that metadata in the expressions used in this command tree must belong to.</param>
        /// <param name="edmFunction"></param>
        /// <param name="resultType"></param>
        /// <param name="parameters"></param>
        /// <exception cref="ArgumentNullException"><paramref name="metadata"/>, <paramref name="dataSpace"/> or <paramref name="edmFunction"/> is null</exception>
        /// <exception cref="ArgumentException"><paramref name="dataSpace"/> does not represent a valid data space or
        /// <paramref name="edmFunction">is a composable function</paramref></exception>
        /*CQT_PUBLIC_API(*/ internal /*)*/ DbFunctionCommandTree(MetadataWorkspace metadata, DataSpace dataSpace, EdmFunction edmFunction, TypeUsage resultType, IEnumerable <KeyValuePair <string, TypeUsage> > parameters)
            : base(metadata, dataSpace)
        {
            EntityUtil.CheckArgumentNull(edmFunction, "edmFunction");

            _edmFunction = edmFunction;
            _resultType  = resultType;

            List <string>    paramNames = new List <string>();
            List <TypeUsage> paramTypes = new List <TypeUsage>();

            if (parameters != null)
            {
                foreach (KeyValuePair <string, TypeUsage> paramInfo in parameters)
                {
                    paramNames.Add(paramInfo.Key);
                    paramTypes.Add(paramInfo.Value);
                }
            }

            _parameterNames = paramNames.AsReadOnly();
            _parameterTypes = paramTypes.AsReadOnly();
        }
        public void GenerateFunctionTemplatesWorksForEdmFunctionWithOptionalParameters(bool bound, string[] expects)
        {
            // Arrange
            EdmFunction getSalaray = new EdmFunction("NS", "GetWholeSalary", IntType, isBound: bound, entitySetPathExpression: null, isComposable: false);

            if (bound)
            {
                EdmEntityType customer = new EdmEntityType("NS", "Customer");
                getSalaray.AddParameter("entityset", new EdmCollectionTypeReference(new EdmCollectionType(new EdmEntityTypeReference(customer, false))));
            }

            getSalaray.AddParameter("salary", IntType);
            getSalaray.AddOptionalParameter("minSalary", IntType);
            getSalaray.AddOptionalParameter("maxSalary", IntType);
            getSalaray.AddOptionalParameter("aveSalary", IntType, "129");

            // Act
            var items = getSalaray.GenerateFunctionTemplates();

            // Assert
            Assert.Equal(expects.Length, items.Count);
            Assert.Equal(expects, items);
        }
Example #60
0
        public void EdmApplyExpression()
        {
            var arguments = new IEdmExpression[] { new EdmIntegerConstant(1) };
            var operation = new EdmFunction("NS", "function", new EdmStringTypeReference(EdmCoreModel.Instance.GetPrimitiveType(EdmPrimitiveTypeKind.String), true));
            var e         = new EdmApplyExpression(operation, arguments);

            Assert.AreEqual(EdmExpressionKind.FunctionApplication, e.ExpressionKind, "e.ExpressionKind");
            Assert.AreEqual(operation, e.AppliedFunction, "e.AppliedFunction");
            Assert.AreEqual(arguments, e.Arguments, "e.AppliedFunction");
            Assert.IsFalse(e.IsBad(), "e good");

            this.VerifyThrowsException(typeof(ArgumentNullException), () => new EdmApplyExpression(null, arguments));
            this.VerifyThrowsException(typeof(ArgumentNullException), () => new EdmApplyExpression(null, arguments.AsEnumerable()));
            this.VerifyThrowsException(typeof(ArgumentNullException), () => new EdmApplyExpression(operation, null));
            this.VerifyThrowsException(typeof(ArgumentNullException), () => new EdmApplyExpression(operation, (IEnumerable <IEdmExpression>)null));

            var ee = new MutableEdmApplyExpression();

            Assert.IsNull(ee.AppliedFunction, "ee.AppliedFunction");
            Assert.IsNull(ee.Arguments, "ee.Arguments");
            Assert.IsTrue(ee.IsBad(), "Expression is bad.");
            Assert.AreEqual(2, ee.Errors().Count(), "Expression has no errors");
        }