private static Function CreateCollectionServiceOperation(string name, DataType type)
 {
     return(new Function(name)
     {
         ReturnType = DataTypes.CollectionType.WithElementDataType(type),
         Parameters =
         {
             new FunctionParameter("arg1", type),
             new FunctionParameter("arg2", type),
             new FunctionParameter("arg3", type),
         },
         Annotations =
         {
             new LegacyServiceOperationAnnotation()
             {
                 Method = HttpVerb.Get,
                 ReturnTypeQualifier = ServiceOperationReturnTypeQualifier.IEnumerable,
             },
             new FunctionBodyAnnotation()
             {
                 FunctionBody = LinqBuilder.AnonymousArray(
                     CommonQueryBuilder.FunctionParameterReference("arg1"),
                     CommonQueryBuilder.FunctionParameterReference("arg2"),
                     CommonQueryBuilder.FunctionParameterReference("arg3")),
             },
         }
     });
 }
Example #2
0
        internal static LinqLambdaExpression CreateLambda(QueryExpression source, IEnumerable <KeyValuePair <QueryProperty, QueryConstantExpression> > keys)
        {
            ExceptionUtilities.CheckArgumentNotNull(source, "source");
            ExceptionUtilities.CheckCollectionNotEmpty(keys, "keys");

            QueryType parameterType;

            if (source.ExpressionType.IsUnresolved)
            {
                parameterType = QueryType.Unresolved;
            }
            else
            {
                var queryCollectionType = source.ExpressionType as QueryCollectionType;
                ExceptionUtilities.CheckObjectNotNull(queryCollectionType, "Source expression type was not a collection. Type was: {0}", source.ExpressionType);
                parameterType = queryCollectionType.ElementType;
            }

            var parameter = LinqBuilder.Parameter(ParameterName, parameterType);

            // specifically using the overload of .Property which takes a type because it may have already been resolved and we don't want to throw that away
            var predicate = keys.Select(k => parameter.Property(k.Key.Name, k.Key.PropertyType).EqualTo(k.Value)).ToList();

            QueryExpression body = predicate[0];

            if (predicate.Count > 1)
            {
                for (int i = 1; i < predicate.Count; i++)
                {
                    body = CommonQueryBuilder.And(body, predicate[i]);
                }
            }

            return(LinqBuilder.Lambda(body, parameter));
        }
Example #3
0
            public override QueryExpression Visit(QueryRootExpression expression)
            {
                var entitySetPropertyInfo = expression.GetType().GetProperties(false, false).Where(p => p.Name == "UnderlyingEntitySet").Single();
                var entitySet             = (EntitySet)entitySetPropertyInfo.GetValue(expression, null);

                return(CommonQueryBuilder.Root(entitySet));
            }
 private static Function CreateMultipleEntityServiceOperation(string name, string entitySetName, string entityTypeName, string propertyName, DataType type)
 {
     return(new Function(name)
     {
         ReturnType = DataTypes.CollectionOfEntities(entityTypeName),
         Parameters =
         {
             new FunctionParameter("arg", type),
         },
         Annotations =
         {
             new LegacyServiceOperationAnnotation()
             {
                 Method = HttpVerb.Get,
                 ReturnTypeQualifier = ServiceOperationReturnTypeQualifier.IQueryable,
             },
             new FunctionBodyAnnotation()
             {
                 FunctionBodyGenerator =
                     (EntityModelSchema model) =>
                 {
                     var entitySet = model.EntityContainers.SelectMany(c => c.EntitySets).Single(s => s.Name == entitySetName);
                     return CommonQueryBuilder.Root(entitySet).Where(o => o.Property(propertyName).GreaterThan(CommonQueryBuilder.FunctionParameterReference("arg")));
                 },
             },
         }
     });
 }
Example #5
0
            public override QueryExpression Visit(QueryPropertyExpression expression)
            {
                var pseudoLocalizedName = this.pseudoLocalizeFunc(expression.Name);
                var instance            = this.ReplaceExpression(expression.Instance);

                return(CommonQueryBuilder.Property(instance, pseudoLocalizedName));
            }
Example #6
0
        /// <summary>
        /// Gets a queryExpression that represents a Query to an existing entity
        /// </summary>
        /// <param name="entityParameter">The LinqParameterExpression which represents the root parameter</param>
        /// <param name="existingEntity">The structural value representing an existing entity</param>
        /// <returns>A QueryExpression representing a query to an existing entity</returns>
        protected static QueryExpression GetExistingEntityKeyComparisonExpression(QueryExpression entityParameter, QueryStructuralValue existingEntity)
        {
            QueryExpression keyFilterExpression = null;
            QueryEntityType entityType          = existingEntity.Type as QueryEntityType;

            foreach (var keyProperty in entityType.EntityType.AllKeyProperties)
            {
                var queryProperty = entityType.Properties.SingleOrDefault(p => p.Name == keyProperty.Name);
                ExceptionUtilities.CheckObjectNotNull(queryProperty, "Could not find property with name '{0}' on type '{1}'", keyProperty.Name, entityType);

                var             value          = existingEntity.GetScalarValue(keyProperty.Name);
                QueryExpression keyComparision = entityParameter.Property(keyProperty.Name).EqualTo(CommonQueryBuilder.Constant(value));

                if (keyFilterExpression == null)
                {
                    keyFilterExpression = keyComparision;
                }
                else
                {
                    keyFilterExpression = CommonQueryBuilder.And(keyFilterExpression, keyComparision);
                }
            }

            return(keyFilterExpression);
        }
        /// <summary>
        /// Creates a Function that takes one or more arguments, and returns the first of its arguments
        /// </summary>
        /// <param name="name">
        /// The name of the function
        /// </param>
        /// <param name="firstArgumentType">The type of the first argument for the function</param>
        /// <param name="otherArgumentsTypes">The types of the rest of the arguments for the function</param>
        /// <returns> A Function that returns the first of its parameters.</returns>
        public static Function CreateSimpleServiceOperation(string name, DataType firstArgumentType, params DataType[] otherArgumentsTypes)
        {
            ExceptionUtilities.CheckArgumentNotNull(name, "name");
            ExceptionUtilities.CheckArgumentNotNull(firstArgumentType, "firstArgumentType");
            ExceptionUtilities.CheckArgumentNotNull(otherArgumentsTypes, "otherArgumentsTypes");

            var function = new Function(name)
            {
                ReturnType = firstArgumentType,
                Parameters =
                {
                    new FunctionParameter("arg0", firstArgumentType),
                },
                Annotations =
                {
                    new LegacyServiceOperationAnnotation()
                    {
                        Method = HttpVerb.Get
                    },
                    new FunctionBodyAnnotation()
                    {
                        FunctionBody = CommonQueryBuilder.FunctionParameterReference("arg0"),
                    },
                }
            };

            for (int i = 0; i < otherArgumentsTypes.Length; i++)
            {
                function.Parameters.Add(new FunctionParameter("arg" + (i + 1).ToString(CultureInfo.InvariantCulture), otherArgumentsTypes[i]));
            }

            return(function);
        }
Example #8
0
        /// <summary>
        /// Builds a constant expression designed to be used in query filters. The constant is one that is likely to return results although
        /// results are not guaranteed.
        /// </summary>
        /// <param name="rootExpression">The <cref>QueryRootExpression</cref> that contains the property used to generate the constant.</param>
        /// <param name="propertyPaths">The paths to the property.</param>
        /// <returns>A constant expression matching the property's type</returns>
        public QueryConstantExpression GetConstantForProperty(QueryRootExpression rootExpression, string[] propertyPaths)
        {
            var dataRows = this.DataSet[rootExpression.Name].Elements.Cast <QueryStructuralValue>();

            IEnumerable <QueryScalarValue> propertyDataSet =
                this.GetPropertyRows(
                    dataRows,
                    propertyPaths.ToList <string>(),
                    ((QueryCollectionType <QueryStructuralType>)rootExpression.ExpressionType).ElementType);

            return(CommonQueryBuilder.Constant(this.SelectRelevantValue(propertyDataSet)));
        }
 /// <summary>
 /// Build function body to return all entities of given entity type.
 /// </summary>
 /// <param name="entityTypeName">the entity type name</param>
 /// <returns>FunctionBodyAnnotation  respresenting the function body</returns>
 public static FunctionBodyAnnotation BuildReturnEntitySetFunctionBody(string entityTypeName)
 {
     return(new FunctionBodyAnnotation
     {
         IsRoot = true,
         FunctionBodyGenerator = (schema) =>
         {
             var entitySet = schema.GetDefaultEntityContainer().EntitySets.Single(es => es.EntityType.Name.Equals(entityTypeName));
             return CommonQueryBuilder.Root(entitySet);
         },
     });
 }
Example #10
0
        public void TaupoQueryTest()
        {
            var entitySet = this.Workspace.ConceptualModel.EntityContainers.First().EntitySets.SingleOrDefault(e => e.Name == "Customer");
            var root      = CommonQueryBuilder.Root(entitySet);
            var query     = root.Where(c => c.Property("CustomerId").EqualTo(CommonQueryBuilder.Constant(1)));

            this.Verifier.Verify(query);

            entitySet = this.Workspace.ConceptualModel.EntityContainers.First().EntitySets.SingleOrDefault(e => e.Name == "Customer");
            root      = CommonQueryBuilder.Root(entitySet);
            query     = root.OrderBy(cust => cust.Property("CustomerId"));
            this.Verifier.Verify(query);
        }
Example #11
0
            public override QueryExpression Visit(QueryConstantExpression expression)
            {
                var oldValue = expression.ScalarValue.Value as string;

                if (oldValue != null)
                {
                    return(CommonQueryBuilder.Constant(this.pseudoLocalizeFunc(oldValue), expression.ExpressionType));
                }
                else
                {
                    return(expression);
                }
            }
Example #12
0
        /// <summary>
        /// Evaluates the given lambda as if it were called on the given entity. Used for evaluating orderby expressions for the last result in a feed.
        /// </summary>
        /// <param name="entity">The entity to evaluate the lambda for.</param>
        /// <param name="lamda">The lamda to evaluate.</param>
        /// <returns>The result of evaluating the lamda for the given entity.</returns>
        private object EvaluateLambdaForEntity(QueryStructuralValue entity, LinqLambdaExpression lamda)
        {
            var expression = CommonQueryBuilder.Root("fakeSet", entity.Type.CreateCollectionType()).Select(lamda).Single();

            var fakeQueryDataSet = new QueryDataSet();

            fakeQueryDataSet.RootQueryData["fakeSet"] = entity.Type.CreateCollectionType().CreateCollectionWithValues(new[] { entity });

            QueryValue evaluated;

            using (this.ExpressionEvaluator.WithTemporaryDataSet(fakeQueryDataSet))
            {
                evaluated = this.ExpressionEvaluator.Evaluate(expression);
            }

            return(((QueryScalarValue)evaluated).Value);
        }
 private static Function CreateSimpleServiceOperation(string name, DataType type)
 {
     return(new Function(name)
     {
         ReturnType = type,
         Parameters =
         {
             new FunctionParameter("arg", type),
         },
         Annotations =
         {
             new LegacyServiceOperationAnnotation()
             {
                 Method = HttpVerb.Get
             },
             new FunctionBodyAnnotation()
             {
                 FunctionBody = CommonQueryBuilder.FunctionParameterReference("arg"),
             },
         }
     });
 }
        private static Function CreateSingleEntityServiceOperation(string name, string entitySetName, string entityTypeName, string propertyName, DataType type)
        {
            return(new Function(name)
            {
                ReturnType = DataTypes.EntityType.WithName(entityTypeName),
                Parameters =
                {
                    new FunctionParameter("arg", type),
                },
                Annotations =
                {
                    new LegacyServiceOperationAnnotation()
                    {
                        Method = HttpVerb.Get,
                        ReturnTypeQualifier = ServiceOperationReturnTypeQualifier.IQueryable,
                        SingleResult = true,
                    },
                    new FunctionBodyAnnotation()
                    {
                        FunctionBodyGenerator =
                            (EntityModelSchema model) =>
                        {
                            var entitySet = model.EntityContainers.SelectMany(c => c.EntitySets).Single(s => s.Name == entitySetName);

                            Func <LinqParameterExpression, QueryExpression> lambdaWithoutNullCheck = o => o.Property(propertyName).GreaterThan(CommonQueryBuilder.FunctionParameterReference("arg"));
                            Func <LinqParameterExpression, QueryExpression> lambda = lambdaWithoutNullCheck;
                            if (type.IsNullable)
                            {
                                lambda = o => lambdaWithoutNullCheck(o).And(o.Property(propertyName).IsNotNull());
                            }

                            return CommonQueryBuilder.Root(entitySet).Where(lambda).Take(1);
                        },
                    },
                }
            });
        }
Example #15
0
        /// <summary>
        /// Factory method to create the <see cref="LinqToAstoriaKeyExpression"/>.
        /// </summary>
        /// <param name="source">The source query.</param>
        /// <param name="keys">The set of key property values.</param>
        /// <returns>The <see cref="QueryExpression"/> with the provided arguments.</returns>
        public static LinqToAstoriaKeyExpression Key(this QueryExpression source, IEnumerable <NamedValue> keys)
        {
            ExceptionUtilities.CheckArgumentNotNull(source, "source");
            ExceptionUtilities.CheckCollectionNotEmpty(keys, "keys");

            QueryType elementType         = QueryType.Unresolved;
            var       queryCollectionType = source.ExpressionType as QueryCollectionType;

            if (queryCollectionType != null)
            {
                elementType = queryCollectionType.ElementType;
            }

            var structuralType = elementType as QueryStructuralType;

            var key = new List <KeyValuePair <QueryProperty, QueryConstantExpression> >();

            foreach (var keyValue in keys)
            {
                QueryScalarType primitiveType = QueryType.UnresolvedPrimitive;
                QueryProperty   queryProperty = QueryProperty.Create(keyValue.Name, primitiveType);

                if (structuralType != null)
                {
                    queryProperty = structuralType.Properties.SingleOrDefault(p => p.Name == keyValue.Name);
                    ExceptionUtilities.CheckObjectNotNull(queryProperty, "Could not find property with name '{0}' on type '{1}'", keyValue.Name, structuralType);

                    primitiveType = queryProperty.PropertyType as QueryScalarType;
                    ExceptionUtilities.CheckObjectNotNull(primitiveType, "Property '{0}' on type '{1}' was not a primitive type", keyValue.Name, structuralType);
                }

                var value = CommonQueryBuilder.Constant(keyValue.Value, primitiveType);
                key.Add(new KeyValuePair <QueryProperty, QueryConstantExpression>(queryProperty, value));
            }

            return(new LinqToAstoriaKeyExpression(source, key, source.ExpressionType));
        }
Example #16
0
        /// <summary>
        /// Gets a queryExpression that represents a Query to an existing entity
        /// </summary>
        /// <param name="rootQuery"> The root query expression of the set</param>
        /// <param name="existingEntity">The structural value representing an existing entity</param>
        /// <returns>A QueryExpression representing a query to an existing entity</returns>
        /// <remarks>
        /// 1. We don't use the .Key syntax because :
        ///     Key forces the Query option to take on the Key FOrmat
        ///     /Customers('ALFKI')
        ///     We change the query to be  Customers?$filter=Id eq 'ALFKI' and true so that we don't use the key syntax as it doesn't work with Live servers.
        /// 2. We append the 'and true' part because :
        ///     If you use the client library and completely cover the key, the client's linq translator will use the key syntax.
        ///     To avoid this, we completely cover the key and also add the 'true" so that the client doesn't produce a key expression string.
        /// </remarks>
        protected internal static QueryExpression GetExistingEntityQuery(QueryExpression rootQuery, QueryStructuralValue existingEntity)
        {
            // We cannot create new LinqParameterExpressions as we track the parameters by name, we need to reuse the parameter from the root query
            Func <LinqParameterExpression, QueryExpression> generateFilterExpression = (entityParameter) =>
            {
                QueryExpression keyFilterExpression = GetExistingEntityKeyComparisonExpression(entityParameter, existingEntity);
                return(keyFilterExpression);
            };

            var query = rootQuery.Where(eParam => generateFilterExpression(eParam).And(CommonQueryBuilder.Constant(true, existingEntity.Type.EvaluationStrategy.BooleanType)));

            return(query);
        }
Example #17
0
        /// <summary>
        /// Factory method to create the <see cref="LinqToAstoriaKeyExpression"/>.
        /// </summary>
        /// <param name="source">The source query.</param>
        /// <param name="instance">The instance to get key values from.</param>
        /// <returns>The <see cref="QueryExpression"/> with a key matching the values of the given instance.</returns>
        public static LinqToAstoriaKeyExpression Key(this QueryExpression source, QueryStructuralValue instance)
        {
            ExceptionUtilities.CheckArgumentNotNull(source, "source");
            ExceptionUtilities.CheckArgumentNotNull(instance, "instance");

            var entityType = instance.Type as QueryEntityType;

            ExceptionUtilities.CheckObjectNotNull(entityType, "Given structural instance was not an entity. Type was: {0}", instance.Type);

            var key = new List <KeyValuePair <QueryProperty, QueryConstantExpression> >();

            foreach (var keyProperty in entityType.EntityType.AllKeyProperties)
            {
                var queryProperty = entityType.Properties.SingleOrDefault(p => p.Name == keyProperty.Name);
                ExceptionUtilities.CheckObjectNotNull(queryProperty, "Could not find property with name '{0}' on type '{1}'", keyProperty.Name, entityType);

                var value = instance.GetScalarValue(keyProperty.Name);

                key.Add(new KeyValuePair <QueryProperty, QueryConstantExpression>(queryProperty, CommonQueryBuilder.Constant(value)));
            }

            return(new LinqToAstoriaKeyExpression(source, key, entityType.CreateCollectionType()));
        }
Example #18
0
        protected virtual void BuildConstants(QueryTypeLibrary queryTypeLibrary, IQueryDataSet dataSet)
        {
            ExceptionUtilities.CheckObjectNotNull(this.RootQueries, "Build root queries first before building constants");

            List <QueryConstantExpression> queryConstants = new List <QueryConstantExpression>();
            var rootQueries = this.RootQueries.OfType <QueryRootExpression>();

            int constantsOfSameTypeLimit = 5;

            foreach (var rootQuery in rootQueries)
            {
                var entityElements = dataSet[rootQuery.Name].Elements;

                if (entityElements.Count() == 0)
                {
                    continue;
                }

                var dataRow           = this.Random.ChooseFrom(entityElements.Cast <QueryStructuralValue>());
                var scalarDataValues  = dataRow.Type.Properties.Where(p => p.PropertyType is QueryScalarType).Select(st => dataRow.GetScalarValue(st.Name)).ToList();
                var complexDataValues = dataRow.Type.Properties.Where(p => p.PropertyType is QueryComplexType).Select(ct => dataRow.GetStructuralValue(ct.Name)).ToList();

                while (complexDataValues.Count() > 0)
                {
                    var complexDataValue = complexDataValues.First();

                    foreach (var propertyName in complexDataValue.MemberNames)
                    {
                        var complexPropertyValue = complexDataValue.GetValue(propertyName);
                        var nestedComplexValue   = complexPropertyValue as QueryStructuralValue;
                        var nestedScalarValue    = complexPropertyValue as QueryScalarValue;

                        if (nestedComplexValue != null)
                        {
                            complexDataValues.Add(nestedComplexValue);
                        }
                        else if (nestedScalarValue != null)
                        {
                            scalarDataValues.Add(nestedScalarValue);
                        }
                    }

                    complexDataValues.Remove(complexDataValue);
                }

                this.AddDefaultConstants(scalarDataValues, queryTypeLibrary);

                foreach (var scalarTypeValue in scalarDataValues)
                {
                    if (queryConstants.Count(qce => qce.ExpressionType.IsSameQueryScalarType(scalarTypeValue.Type as QueryScalarType)) <= constantsOfSameTypeLimit)
                    {
                        queryConstants.Add(CommonQueryBuilder.Constant(scalarTypeValue));
                    }
                }
            }

            var nonMappedEnumTypes = queryTypeLibrary.GetNonMappedEnumTypes();

            foreach (var nonMappedEnum in nonMappedEnumTypes)
            {
                var enumMember      = this.Random.ChooseFrom(nonMappedEnum.EnumType.Members);
                var enumObjectToAdd = Enum.Parse(nonMappedEnum.ClrType, enumMember.Name, false);

                queryConstants.Add(CommonQueryBuilder.Constant(enumObjectToAdd));
            }

            this.Constants = queryConstants.AsEnumerable();
        }
        public EntityModelSchema GenerateModel()
        {
            var model = new EntityModelSchema()
            {
                new EntityType("Customer")
                {
                    new MemberProperty("CustomerId", DataTypes.Integer)
                    {
                        IsPrimaryKey = true
                    },
                    new MemberProperty("Name", DataTypes.String.WithMaxLength(100)).WithDataGenerationHints(DataGenerationHints.InterestingValue <string>(string.Empty), DataGenerationHints.AnsiString, DataGenerationHints.MinLength(3)),
                    new MemberProperty("PrimaryContactInfo", DataTypes.ComplexType.WithName("ContactDetails")),
                    new MemberProperty("BackupContactInfo", DataTypes.CollectionType.WithElementDataType(DataTypes.ComplexType.WithName("ContactDetails"))),
                    new MemberProperty("Auditing", DataTypes.ComplexType.WithName("AuditInfo")),
                    new MemberProperty("Thumbnail", DataTypes.Stream),
                    new MemberProperty("Video", DataTypes.Stream),
                    new MemberProperty("MembershipDuration", DataTypes.DateTime.WithTimeZoneOffset(true)),
                    new NavigationProperty("Orders", "Customer_Orders", "Customer", "Order"),
                    new NavigationProperty("Logins", "Customer_Logins", "Customer", "Logins"),
                    new NavigationProperty("Husband", "Husband_Wife", "Wife", "Husband"),
                    new NavigationProperty("Wife", "Husband_Wife", "Husband", "Wife"),
                    new NavigationProperty("Info", "Customer_CustomerInfo", "Customer", "Info"),
                },
                new ComplexType("Aliases")
                {
                    new MemberProperty("AlternativeNames", DataTypes.CollectionType.WithElementDataType(DataTypes.String.WithMaxLength(10))),
                },
                new ComplexType("Phone")
                {
                    new MemberProperty("PhoneNumber", DataTypes.String.WithMaxLength(16)),
                    new MemberProperty("Extension", DataTypes.String.WithMaxLength(16).Nullable(true)),
                },
                new ComplexType("ContactDetails")
                {
                    new MemberProperty("EmailBag", DataTypes.CollectionType.WithElementDataType(DataTypes.String.WithMaxLength(32))),
                    new MemberProperty("AlternativeNames", DataTypes.CollectionType.WithElementDataType(DataTypes.String.WithMaxLength(10))),
                    new MemberProperty("ContactAlias", DataTypes.ComplexType.WithName("Aliases")),
                    new MemberProperty("HomePhone", DataTypes.ComplexType.WithName("Phone")),
                    new MemberProperty("WorkPhone", DataTypes.ComplexType.WithName("Phone")),
                    new MemberProperty("MobilePhoneBag", DataTypes.CollectionType.WithElementDataType(DataTypes.ComplexType.WithName("Phone"))),
                },
                new ComplexType("ComplexToCategory")
                {
                    new MemberProperty("Term", DataTypes.String).WithDataGenerationHints(DataGenerationHints.NoNulls, DataGenerationHints.AnsiString, DataGenerationHints.MinLength(3)),
                    new MemberProperty("Scheme", DataTypes.String).WithDataGenerationHints(DataGenerationHints.StringPrefixHint("http://"), DataGenerationHints.NoNulls, DataGenerationHints.AnsiString, DataGenerationHints.MinLength(10), DataGenerationHints.MaxLength(30)),
                    new MemberProperty("Label", DataTypes.String).WithDataGenerationHints(DataGenerationHints.NoNulls, DataGenerationHints.AnsiString, DataGenerationHints.MinLength(3)),
                },
                new EntityType("Login")
                {
                    new MemberProperty("Username", DataTypes.String.WithMaxLength(50))
                    {
                        IsPrimaryKey = true
                    },
                    new MemberProperty("CustomerId", DataTypes.Integer),
                    new NavigationProperty("Customer", "Customer_Logins", "Logins", "Customer"),
                    new NavigationProperty("LastLogin", "Login_LastLogin", "Login", "LastLogin"),
                    new NavigationProperty("SentMessages", "Login_SentMessages", "Sender", "Message"),
                    new NavigationProperty("ReceivedMessages", "Login_ReceivedMessages", "Recipient", "Message"),
                    new NavigationProperty("Orders", "Login_Orders", "Login", "Orders"),
                },
                new EntityType("RSAToken")
                {
                    new MemberProperty("Serial", DataTypes.String.WithMaxLength(20))
                    {
                        IsPrimaryKey = true
                    },
                    new MemberProperty("Issued", DataTypes.DateTime),
                    new NavigationProperty("Login", "Login_RSAToken", "RSAToken", "Login"),
                },
                new EntityType("PageView")
                {
                    new MemberProperty("PageViewId", DataTypes.Integer)
                    {
                        IsPrimaryKey = true
                    },
                    new MemberProperty("Username", DataTypes.String.WithMaxLength(50)),
                    new MemberProperty("Viewed", DataTypes.DateTime.WithTimeZoneOffset(true)),
                    new MemberProperty("TimeSpentOnPage", DataTypes.TimeOfDay),
                    new MemberProperty("PageUrl", DataTypes.String.WithMaxLength(500)).WithDataGenerationHints(DataGenerationHints.NoNulls, DataGenerationHints.MinLength(3)),
                    new NavigationProperty("Login", "Login_PageViews", "PageViews", "Login"),
                },
                new EntityType("ProductPageView")
                {
                    BaseType   = "PageView",
                    Properties =
                    {
                        new MemberProperty("ProductId",        DataTypes.Integer),
                        new MemberProperty("ConcurrencyToken", DataTypes.String)
                        {
                            Annotations = { new ConcurrencyTokenAnnotation() }
                        },
                    }
                },
                new EntityType("LastLogin")
                {
                    new MemberProperty("Username", DataTypes.String.WithMaxLength(50))
                    {
                        IsPrimaryKey = true
                    },
                    new MemberProperty("LoggedIn", DataTypes.DateTime.WithTimeZoneOffset(true).NotNullable()),
                    new MemberProperty("LoggedOut", DataTypes.DateTime.WithTimeZoneOffset(true).NotNullable()),
                    new MemberProperty("Duration", DataTypes.TimeOfDay),
                    new NavigationProperty("Login", "Login_LastLogin", "LastLogin", "Login"),
                },
                new EntityType("Message")
                {
                    new MemberProperty("MessageId", DataTypes.Integer)
                    {
                        IsPrimaryKey = true
                    },
                    new MemberProperty("FromUsername", DataTypes.String.WithMaxLength(50))
                    {
                        IsPrimaryKey = true
                    },
                    new MemberProperty("ToUsername", DataTypes.String.WithMaxLength(50)),
                    new MemberProperty("Sent", DataTypes.DateTime.WithTimeZoneOffset(true)),
                    new MemberProperty("Subject", DataTypes.String.NotNullable()).WithDataGenerationHints(DataGenerationHints.InterestingValue <string>(string.Empty)),
                    new MemberProperty("Body", DataTypes.String.Nullable(true)),
                    new MemberProperty("IsRead", DataTypes.Boolean),
                    new NavigationProperty("Sender", "Login_SentMessages", "Message", "Sender"),
                    new NavigationProperty("Recipient", "Login_ReceivedMessages", "Message", "Recipient"),
                },
                new EntityType("Order")
                {
                    new MemberProperty("OrderId", DataTypes.Integer)
                    {
                        IsPrimaryKey = true
                    },
                    new MemberProperty("CustomerId", DataTypes.Integer.Nullable(true)),
                    new MemberProperty("Concurrency", DataTypes.ComplexType.WithName("ConcurrencyInfo")),
                    new NavigationProperty("Customer", "Customer_Orders", "Order", "Customer"),
                    new NavigationProperty("Login", "Login_Orders", "Orders", "Login"),
                },
                new EntityType("OrderLine")
                {
                    new MemberProperty("OrderId", DataTypes.Integer)
                    {
                        IsPrimaryKey = true
                    },
                    new MemberProperty("ProductId", DataTypes.Integer)
                    {
                        IsPrimaryKey = true
                    },
                    new MemberProperty("Quantity", DataTypes.Integer),
                    new MemberProperty("ConcurrencyToken", DataTypes.String)
                    {
                        Annotations = { new ConcurrencyTokenAnnotation() }
                    },
                    new MemberProperty("OrderLineStream", DataTypes.Stream),
                    new NavigationProperty("Order", "Order_OrderLines", "OrderLines", "Order"),
                    new NavigationProperty("Product", "Product_OrderLines", "OrderLines", "Product"),
                },
                new EntityType("BackOrderLine")
                {
                    BaseType = "OrderLine"
                },
                new EntityType("BackOrderLine2")
                {
                    BaseType = "BackOrderLine",
                },
                new ComplexType("Dimensions")
                {
                    new MemberProperty("Width", DataTypes.FixedPoint.WithPrecision(10).WithScale(3)),
                    new MemberProperty("Height", DataTypes.FixedPoint.WithPrecision(10).WithScale(3)),
                    new MemberProperty("Depth", DataTypes.FixedPoint.WithPrecision(10).WithScale(3)),
                },
                new EntityType("Product")
                {
                    new MemberProperty("ProductId", DataTypes.Integer)
                    {
                        IsPrimaryKey = true
                    },
                    new MemberProperty("Description", DataTypes.String.Nullable(true).WithUnicodeSupport(true).WithMaxLength(1000)),
                    new MemberProperty("Dimensions", DataTypes.ComplexType.WithName("Dimensions")),
                    new MemberProperty("BaseConcurrency", DataTypes.String)
                    {
                        Annotations = { new ConcurrencyTokenAnnotation() }
                    },
                    new MemberProperty("ComplexConcurrency", DataTypes.ComplexType.WithName("ConcurrencyInfo")),
                    new MemberProperty("NestedComplexConcurrency", DataTypes.ComplexType.WithName("AuditInfo")),
                    new MemberProperty("Picture", DataTypes.Stream),
                    new NavigationProperty("RelatedProducts", "Products_RelatedProducts", "Product", "RelatedProducts"),
                    new NavigationProperty("Detail", "Product_ProductDetail", "Product", "ProductDetail"),
                    new NavigationProperty("Reviews", "Product_ProductReview", "Product", "ProductReview"),
                    new NavigationProperty("Photos", "Product_ProductPhoto", "Product", "ProductPhoto"),
                },
                new EntityType("DiscontinuedProduct")
                {
                    BaseType   = "Product",
                    Properties =
                    {
                        new MemberProperty("Discontinued",          DataTypes.DateTime),
                        new MemberProperty("ReplacementProductId",  DataTypes.Integer.Nullable()),
                        new MemberProperty("DiscontinuedPhone",     DataTypes.ComplexType.WithName("Phone")),
                        new MemberProperty("ChildConcurrencyToken", DataTypes.String)
                        {
                            Annotations = { new ConcurrencyTokenAnnotation() }
                        },
                    },
                },
                new EntityType("ProductDetail")
                {
                    new MemberProperty("ProductId", DataTypes.Integer)
                    {
                        IsPrimaryKey = true
                    },
                    new MemberProperty("Details", DataTypes.String),
                    new NavigationProperty("Product", "Product_ProductDetail", "ProductDetail", "Product"),
                },
                new EntityType("ProductReview")
                {
                    new MemberProperty("ProductId", DataTypes.Integer)
                    {
                        IsPrimaryKey = true
                    },
                    new MemberProperty("ReviewId", DataTypes.Integer)
                    {
                        IsPrimaryKey = true
                    },
                    new MemberProperty("Review", DataTypes.String),
                    new NavigationProperty("Product", "Product_ProductReview", "ProductReview", "Product"),
                },
                new EntityType("ProductPhoto")
                {
                    new MemberProperty("ProductId", DataTypes.Integer)
                    {
                        IsPrimaryKey = true
                    },
                    new MemberProperty("PhotoId", DataTypes.Integer)
                    {
                        IsPrimaryKey = true
                    },
                    new MemberProperty("Photo", DataTypes.Binary),
                },
                new EntityType("CustomerInfo")
                {
                    new MemberProperty("CustomerInfoId", DataTypes.Integer)
                    {
                        IsPrimaryKey = true
                    },
                    new MemberProperty("Information", DataTypes.String.Nullable()),
                    new HasStreamAnnotation(),
                },
                new EntityType("Computer")
                {
                    new MemberProperty("ComputerId", DataTypes.Integer)
                    {
                        IsPrimaryKey = true
                    },
                    new MemberProperty("Name", DataTypes.String),
                    new NavigationProperty("ComputerDetail", "Computer_ComputerDetail", "Computer", "ComputerDetail"),
                },
                new EntityType("ComputerDetail")
                {
                    new MemberProperty("ComputerDetailId", DataTypes.Integer)
                    {
                        IsPrimaryKey = true
                    },
                    new MemberProperty("Manufacturer", DataTypes.String).WithDataGenerationHints(DataGenerationHints.InterestingValue <string>(string.Empty)),
                    new MemberProperty("Model", DataTypes.String).WithDataGenerationHints(DataGenerationHints.InterestingValue <string>(string.Empty)),
                    new MemberProperty("Serial", DataTypes.String),
                    new MemberProperty("SpecificationsBag", DataTypes.CollectionType.WithElementDataType(DataTypes.String)),
                    new MemberProperty("PurchaseDate", DataTypes.DateTime),
                    new MemberProperty("Dimensions", DataTypes.ComplexType.WithName("Dimensions")),
                    new NavigationProperty("Computer", "Computer_ComputerDetail", "ComputerDetail", "Computer"),
                },
                new EntityType("Driver")
                {
                    new MemberProperty("Name", DataTypes.String.WithMaxLength(100))
                    {
                        IsPrimaryKey = true
                    },
                    new MemberProperty("BirthDate", DataTypes.DateTime),
                    new NavigationProperty("License", "Driver_License", "Driver", "License"),
                },
                new EntityType("License")
                {
                    new MemberProperty("Name", DataTypes.String.WithMaxLength(100))
                    {
                        IsPrimaryKey = true
                    },
                    new MemberProperty("LicenseNumber", DataTypes.String),
                    new MemberProperty("LicenseClass", DataTypes.String).WithDataGenerationHints(DataGenerationHints.InterestingValue <string>(string.Empty)),
                    new MemberProperty("Restrictions", DataTypes.String).WithDataGenerationHints(DataGenerationHints.InterestingValue <string>(string.Empty)),
                    new MemberProperty("ExpirationDate", DataTypes.DateTime),
                    new NavigationProperty("Driver", "Driver_License", "License", "Driver"),
                },
                new EntityType("MappedEntityType")
                {
                    new MemberProperty("Id", DataTypes.Integer)
                    {
                        IsPrimaryKey = true
                    },
                    new MemberProperty("Href", DataTypes.String).WithDataGenerationHints(DataGenerationHints.NoNulls, DataGenerationHints.AnsiString, DataGenerationHints.MinLength(3)),
                    new MemberProperty("Title", DataTypes.String).WithDataGenerationHints(DataGenerationHints.NoNulls, DataGenerationHints.AnsiString, DataGenerationHints.MinLength(3)),
                    new MemberProperty("HrefLang", DataTypes.String).WithDataGenerationHints(DataGenerationHints.NoNulls, DataGenerationHints.AnsiString, DataGenerationHints.MinLength(3)),
                    new MemberProperty("Type", DataTypes.String).WithDataGenerationHints(DataGenerationHints.NoNulls, DataGenerationHints.AnsiString, DataGenerationHints.MinLength(3)),
                    new MemberProperty("Length", DataTypes.Integer).WithDataGenerationHints(DataGenerationHints.NoNulls, DataGenerationHints.MinValue <int>(100), DataGenerationHints.MaxValue <int>(200)),
                    new MemberProperty("BagOfPrimitiveToLinks", DataTypes.CollectionType.WithElementDataType(DataTypes.String)),
                    new MemberProperty("Logo", DataTypes.Binary.WithMaxLength(500)),
                    new MemberProperty("BagOfDecimals", DataTypes.CollectionType.WithElementDataType(EdmDataTypes.Decimal())),
                    new MemberProperty("BagOfDoubles", DataTypes.CollectionType.WithElementDataType(EdmDataTypes.Double)),
                    new MemberProperty("BagOfSingles", DataTypes.CollectionType.WithElementDataType(EdmDataTypes.Single)),
                    new MemberProperty("BagOfBytes", DataTypes.CollectionType.WithElementDataType(EdmDataTypes.Byte)),
                    new MemberProperty("BagOfInt16s", DataTypes.CollectionType.WithElementDataType(EdmDataTypes.Int16)),
                    new MemberProperty("BagOfInt32s", DataTypes.CollectionType.WithElementDataType(EdmDataTypes.Int32)),
                    new MemberProperty("BagOfInt64s", DataTypes.CollectionType.WithElementDataType(EdmDataTypes.Int64)),
                    new MemberProperty("BagOfGuids", DataTypes.CollectionType.WithElementDataType(EdmDataTypes.Guid)),
                    new MemberProperty("BagOfDateTime", DataTypes.CollectionType.WithElementDataType(EdmDataTypes.DateTime())),
                    new MemberProperty("BagOfComplexToCategories", DataTypes.CollectionType.WithElementDataType(DataTypes.ComplexType.WithName("ComplexToCategory"))),
                    new MemberProperty("CollectionOfDateTimeOffset", DataTypes.CollectionType.WithElementDataType(DataTypes.DateTime.WithTimeZoneOffset(true))),
                    new MemberProperty("ComplexPhone", DataTypes.ComplexType.WithName("Phone")),
                    new MemberProperty("ComplexContactDetails", DataTypes.ComplexType.WithName("ContactDetails")),
                },
                new EntityType("Car")
                {
                    new MemberProperty("VIN", DataTypes.Integer)
                    {
                        IsPrimaryKey = true
                    },
                    new MemberProperty("Description", DataTypes.String.WithMaxLength(100).Nullable(true)),
                    new MemberProperty("Photo", DataTypes.Stream),
                    new MemberProperty("Video", DataTypes.Stream),
                    new HasStreamAnnotation(),
                },
                new ComplexType("AuditInfo")
                {
                    new MemberProperty("ModifiedDate", DataTypes.DateTime),
                    new MemberProperty("ModifiedBy", DataTypes.String.WithMaxLength(50)),
                    new MemberProperty("Concurrency", DataTypes.ComplexType.WithName("ConcurrencyInfo")),
                },
                new ComplexType("ConcurrencyInfo")
                {
                    new MemberProperty("Token", DataTypes.String.WithMaxLength(20)),
                    new MemberProperty("QueriedDateTime", DataTypes.DateTime.Nullable(true)),
                },
                new AssociationType("Login_SentMessages")
                {
                    new AssociationEnd("Sender", "Login", EndMultiplicity.One),
                    new AssociationEnd("Message", "Message", EndMultiplicity.Many),
                    new ReferentialConstraint()
                    .WithDependentProperties("Message", "FromUsername")
                    .ReferencesPrincipalProperties("Sender", "Username"),
                },
                new AssociationType("Login_ReceivedMessages")
                {
                    new AssociationEnd("Recipient", "Login", EndMultiplicity.One),
                    new AssociationEnd("Message", "Message", EndMultiplicity.Many),
                    new ReferentialConstraint()
                    .WithDependentProperties("Message", "ToUsername")
                    .ReferencesPrincipalProperties("Recipient", "Username"),
                },
                new AssociationType("Customer_CustomerInfo")
                {
                    new AssociationEnd("Customer", "Customer", EndMultiplicity.One),
                    new AssociationEnd("Info", "CustomerInfo", EndMultiplicity.ZeroOne),
                },
                new AssociationType("Login_Orders")
                {
                    new AssociationEnd("Login", "Login", EndMultiplicity.ZeroOne),
                    new AssociationEnd("Orders", "Order", EndMultiplicity.Many),
                },
                new AssociationType("Customer_Orders")
                {
                    new AssociationEnd("Customer", "Customer", EndMultiplicity.ZeroOne),
                    new AssociationEnd("Order", "Order", EndMultiplicity.Many),
                    new ReferentialConstraint()
                    .WithDependentProperties("Order", "CustomerId")
                    .ReferencesPrincipalProperties("Customer", "CustomerId"),
                },
                new AssociationType("Customer_Logins")
                {
                    new AssociationEnd("Customer", "Customer", EndMultiplicity.One),
                    new AssociationEnd("Logins", "Login", EndMultiplicity.Many),
                    new ReferentialConstraint()
                    .WithDependentProperties("Logins", "CustomerId")
                    .ReferencesPrincipalProperties("Customer", "CustomerId"),
                },
                new AssociationType("Login_LastLogin")
                {
                    new AssociationEnd("Login", "Login", EndMultiplicity.One),
                    new AssociationEnd("LastLogin", "LastLogin", EndMultiplicity.ZeroOne),
                    new ReferentialConstraint()
                    .WithDependentProperties("LastLogin", "Username")
                    .ReferencesPrincipalProperties("Login", "Username"),
                },
                new AssociationType("Order_OrderLines")
                {
                    new AssociationEnd("Order", "Order", EndMultiplicity.One),
                    new AssociationEnd("OrderLines", "OrderLine", EndMultiplicity.Many),
                    new ReferentialConstraint()
                    .WithDependentProperties("OrderLines", "OrderId")
                    .ReferencesPrincipalProperties("Order", "OrderId"),
                },
                new AssociationType("Product_OrderLines")
                {
                    new AssociationEnd("Product", "Product", EndMultiplicity.One),
                    new AssociationEnd("OrderLines", "OrderLine", EndMultiplicity.Many),
                    new ReferentialConstraint()
                    .WithDependentProperties("OrderLines", "ProductId")
                    .ReferencesPrincipalProperties("Product", "ProductId"),
                },
                new AssociationType("Products_RelatedProducts")
                {
                    new AssociationEnd("Product", "Product", EndMultiplicity.One),
                    new AssociationEnd("RelatedProducts", "Product", EndMultiplicity.Many),
                },
                new AssociationType("Product_ProductDetail")
                {
                    new AssociationEnd("Product", "Product", EndMultiplicity.One),
                    new AssociationEnd("ProductDetail", "ProductDetail", EndMultiplicity.ZeroOne),
                    new ReferentialConstraint()
                    .WithDependentProperties("ProductDetail", "ProductId")
                    .ReferencesPrincipalProperties("Product", "ProductId"),
                },
                new AssociationType("Product_ProductReview")
                {
                    new AssociationEnd("Product", "Product", EndMultiplicity.One),
                    new AssociationEnd("ProductReview", "ProductReview", EndMultiplicity.Many),
                    new ReferentialConstraint()
                    .WithDependentProperties("ProductReview", "ProductId")
                    .ReferencesPrincipalProperties("Product", "ProductId"),
                },
                new AssociationType("Product_ProductPhoto")
                {
                    new AssociationEnd("Product", "Product", EndMultiplicity.One),
                    new AssociationEnd("ProductPhoto", "ProductPhoto", EndMultiplicity.Many),
                    new ReferentialConstraint()
                    .WithDependentProperties("ProductPhoto", "ProductId")
                    .ReferencesPrincipalProperties("Product", "ProductId"),
                },
                new AssociationType("Husband_Wife")
                {
                    new AssociationEnd("Husband", "Customer", EndMultiplicity.ZeroOne)
                    {
                        Annotations = { new PrincipalAnnotation() }
                    },
                    new AssociationEnd("Wife", "Customer", EndMultiplicity.ZeroOne),
                },
                new AssociationType("Login_RSAToken")
                {
                    new AssociationEnd("Login", "Login", EndMultiplicity.One),
                    new AssociationEnd("RSAToken", "RSAToken", EndMultiplicity.ZeroOne),
                },
                new AssociationType("Login_PageViews")
                {
                    new AssociationEnd("Login", "Login", EndMultiplicity.One),
                    new AssociationEnd("PageViews", "PageView", EndMultiplicity.Many),
                    new ReferentialConstraint()
                    .WithDependentProperties("PageViews", "Username")
                    .ReferencesPrincipalProperties("Login", "Username"),
                },
                new AssociationType("Computer_ComputerDetail")
                {
                    new AssociationEnd("Computer", "Computer", EndMultiplicity.One)
                    {
                        Annotations = { new PrincipalAnnotation() }
                    },
                    new AssociationEnd("ComputerDetail", "ComputerDetail", EndMultiplicity.One),
                },
                new AssociationType("Driver_License")
                {
                    new AssociationEnd("Driver", "Driver", EndMultiplicity.One),
                    new AssociationEnd("License", "License", EndMultiplicity.One),
                    new ReferentialConstraint()
                    .WithDependentProperties("License", "Name")
                    .ReferencesPrincipalProperties("Driver", "Name"),
                },
                new EntityType("Person")
                {
                    new MemberProperty("PersonId", DataTypes.Integer)
                    {
                        IsPrimaryKey = true
                    },
                    new MemberProperty("Name", DataTypes.String).WithDataGenerationHints(DataGenerationHints.NoNulls, DataGenerationHints.MinLength(3)),
                    new NavigationProperty("PersonMetadata", "Person_PersonMetadata", "Person", "PersonMetadata"),
                },
                new EntityType("Employee")
                {
                    BaseType   = "Person",
                    Properties =
                    {
                        new MemberProperty("ManagersPersonId", DataTypes.Integer),
                        new MemberProperty("Salary",           DataTypes.Integer),
                        new MemberProperty("Title",            DataTypes.String).WithDataGenerationHints(DataGenerationHints.NoNulls,DataGenerationHints.MinLength(3)),
                    },
                    NavigationProperties =
                    {
                        new NavigationProperty("Manager", "Employee_Manager", "Employee", "Manager"),
                    },
                },
                new EntityType("SpecialEmployee")
                {
                    BaseType   = "Employee",
                    Properties =
                    {
                        new MemberProperty("CarsVIN",       DataTypes.Integer),
                        new MemberProperty("Bonus",         DataTypes.Integer),
                        new MemberProperty("IsFullyVested", DataTypes.Boolean),
                    },
                    NavigationProperties =
                    {
                        new NavigationProperty("Car", "SpecialEmployee_Car", "SpecialEmployee", "Car"),
                    }
                },
                new EntityType("PersonMetadata")
                {
                    new MemberProperty("PersonMetadataId", DataTypes.Integer)
                    {
                        IsPrimaryKey = true
                    },
                    new MemberProperty("PersonId", DataTypes.Integer),
                    new MemberProperty("PropertyName", DataTypes.String),
                    new MemberProperty("PropertyValue", DataTypes.String),
                    new NavigationProperty("Person", "Person_PersonMetadata", "PersonMetadata", "Person"),
                },
                new AssociationType("Person_PersonMetadata")
                {
                    new AssociationEnd("Person", "Person", EndMultiplicity.One),
                    new AssociationEnd("PersonMetadata", "PersonMetadata", EndMultiplicity.Many),
                    new ReferentialConstraint()
                    .WithDependentProperties("PersonMetadata", "PersonId")
                    .ReferencesPrincipalProperties("Person", "PersonId"),
                },
                new AssociationType("Employee_Manager")
                {
                    new AssociationEnd("Employee", "Employee", EndMultiplicity.Many),
                    new AssociationEnd("Manager", "Employee", EndMultiplicity.One),
                    new ReferentialConstraint()
                    .WithDependentProperties("Employee", "ManagersPersonId")
                    .ReferencesPrincipalProperties("Manager", "PersonId"),
                },
                new AssociationType("SpecialEmployee_Car")
                {
                    new AssociationEnd("SpecialEmployee", "SpecialEmployee", EndMultiplicity.Many),
                    new AssociationEnd("Car", "Car", EndMultiplicity.One),
                    new ReferentialConstraint()
                    .WithDependentProperties("SpecialEmployee", "CarsVIN")
                    .ReferencesPrincipalProperties("Car", "VIN"),
                },
                new Function("GetPrimitiveString")
                {
                    ReturnType  = EdmDataTypes.String().NotNullable(),
                    Annotations =
                    {
                        new LegacyServiceOperationAnnotation
                        {
                            Method = HttpVerb.Get,
                        },
                        new FunctionBodyAnnotation
                        {
                            FunctionBody = CommonQueryBuilder.Constant("Foo"),
                        },
                    },
                },
                new Function("GetSpecificCustomer")
                {
                    ReturnType  = DataTypes.CollectionType.WithElementDataType(DataTypes.EntityType.WithName("Customer")),
                    Annotations =
                    {
                        new LegacyServiceOperationAnnotation
                        {
                            Method = HttpVerb.Get,
                            ReturnTypeQualifier = ServiceOperationReturnTypeQualifier.IEnumerable,
                        },
                        new FunctionBodyAnnotation
                        {
                            FunctionBodyGenerator = (schema) =>
                            {
                                var entitySet = schema.GetDefaultEntityContainer().EntitySets.Where(set => set.Name.Equals("Customer")).Single();
                                return(CommonQueryBuilder.Root(entitySet).Where(c => c.Property("Name").EqualTo(CommonQueryBuilder.FunctionParameterReference("Name"))));
                            },
                        },
                    },
                    Parameters =
                    {
                        new FunctionParameter("Name", EdmDataTypes.String().NotNullable()),
                    },
                },
                new Function("GetCustomerCount")
                {
                    ReturnType  = EdmDataTypes.Int32.NotNullable(),
                    Annotations =
                    {
                        new LegacyServiceOperationAnnotation
                        {
                            Method = HttpVerb.Get,
                        },
                        new FunctionBodyAnnotation
                        {
                            FunctionBodyGenerator = (schema) =>
                            {
                                var entitySet = schema.GetDefaultEntityContainer().EntitySets.Where(set => set.Name.Equals("Customer")).Single();
                                return(CommonQueryBuilder.Root(entitySet).Count());
                            },
                        },
                    },
                },
                new Function("GetArgumentPlusOne")
                {
                    ReturnType  = EdmDataTypes.Int32.NotNullable(),
                    Annotations =
                    {
                        new LegacyServiceOperationAnnotation
                        {
                            Method = HttpVerb.Get,
                        },
                        new FunctionBodyAnnotation
                        {
                            FunctionBody = CommonQueryBuilder.Add(CommonQueryBuilder.FunctionParameterReference("arg1"), CommonQueryBuilder.Constant((int)1)),
                        },
                    },
                    Parameters =
                    {
                        new FunctionParameter("arg1", EdmDataTypes.Int32.NotNullable()),
                    },
                },
                new Function("EntityProjectionReturnsCollectionOfComplexTypes")
                {
                    ReturnType  = DataTypes.CollectionType.WithElementDataType(DataTypes.ComplexType.WithName("ContactDetails")),
                    Annotations =
                    {
                        new LegacyServiceOperationAnnotation {
                            Method = HttpVerb.Get, ReturnTypeQualifier = ServiceOperationReturnTypeQualifier.IEnumerable,
                        },
                        new FunctionBodyAnnotation
                        {
                            FunctionBodyGenerator = (schema) =>
                            {
                                var entitySet = schema.GetDefaultEntityContainer().EntitySets.Where(set => set.Name.Equals("Customer")).Single();
                                return(CommonQueryBuilder.Root(entitySet).Select(e => e.Property("PrimaryContactInfo")));
                            },
                        },
                    },
                },
            };

            // TODO: Add more types for other features like relationship link, streams.
            if (this.RunStability == RunStability.Unstable)
            {
                // Add a service operation for each base entity type
                new AddRootServiceOperationsFixup().Fixup(model);

                // Add some WebInvoke service opeartions covering entity types with navigation, inheritance, concurrency
                this.AddWebInvokeServiceOperations(model);
            }

            // Apply default fixups
            new ResolveReferencesFixup().Fixup(model);
            new ApplyDefaultNamespaceFixup("DefaultNamespace").Fixup(model);
            new AddDefaultContainerFixup().Fixup(model);
            return(model);
        }
Example #20
0
        private void AddServiceOperationsToModel(EntityModelSchema model)
        {
            model.Add(new Function("GetActor")
            {
                ReturnType  = DataTypes.CollectionType.WithElementDataType(DataTypes.EntityType.WithName("Actor")),
                Annotations =
                {
                    new LegacyServiceOperationAnnotation
                    {
                        Method = HttpVerb.Get,
                        ReturnTypeQualifier = ServiceOperationReturnTypeQualifier.IQueryable,
                    },
                    new FunctionBodyAnnotation
                    {
                        //// Enable the following line to add this to root query for cross feature testing
                        //// IsRoot = true,
                        FunctionBodyGenerator = (schema) =>
                        {
                            var entitySet = schema.GetDefaultEntityContainer().EntitySets.Single(es => es.Name.Equals("Actor"));
                            return(CommonQueryBuilder.Root(entitySet));
                        },
                    },
                }
            });

            model.Add(new Function("GetPrimitiveString")
            {
                ReturnType  = EdmDataTypes.String().NotNullable(),
                Annotations =
                {
                    new LegacyServiceOperationAnnotation
                    {
                        Method = HttpVerb.Get,
                    },
                    new FunctionBodyAnnotation
                    {
                        FunctionBody = CommonQueryBuilder.Constant("Foo"),
                    },
                },
            });

            // Add a service operation that requires parameter
            model.Add(new Function("GetArgumentPlusOne")
            {
                ReturnType  = EdmDataTypes.Int32.NotNullable(),
                Annotations =
                {
                    new LegacyServiceOperationAnnotation
                    {
                        Method = HttpVerb.Get,
                    },
                    new FunctionBodyAnnotation
                    {
                        FunctionBody = CommonQueryBuilder.Add(CommonQueryBuilder.FunctionParameterReference("arg1"), CommonQueryBuilder.Constant((int)1)),
                    },
                },
                Parameters =
                {
                    new FunctionParameter("arg1", EdmDataTypes.Int32.NotNullable()),
                },
            });

            // Add a WebInvoke service operation
            model.Add(
                new Function("WebInvokeGetMovie")
            {
                ReturnType  = DataTypes.CollectionType.WithElementDataType(DataTypes.EntityType.WithName("Movie")),
                Annotations =
                {
                    new LegacyServiceOperationAnnotation
                    {
                        Method = HttpVerb.Post,
                        ReturnTypeQualifier = ServiceOperationReturnTypeQualifier.IQueryable,
                    },

                    new FunctionBodyAnnotation
                    {
                        //// Enable the following line to add this to root query for cross feature testing
                        //// IsRoot = true,
                        FunctionBodyGenerator = (schema) =>
                        {
                            var entitySet = schema.GetDefaultEntityContainer().EntitySets.Single(es => es.Name.Equals("Movie"));
                            return(CommonQueryBuilder.Root(entitySet));
                        },
                    }
                },
            });

            model.Add(
                new Function("WebInvokeGetMovieWithParameter")
            {
                ReturnType  = DataTypes.CollectionType.WithElementDataType(DataTypes.EntityType.WithName("Movie")),
                Annotations =
                {
                    new LegacyServiceOperationAnnotation
                    {
                        Method = HttpVerb.Post,
                        ReturnTypeQualifier = ServiceOperationReturnTypeQualifier.IQueryable,
                    },

                    new FunctionBodyAnnotation
                    {
                        FunctionBodyGenerator = (schema) =>
                        {
                            var entitySet = schema.GetDefaultEntityContainer().EntitySets.Single(es => es.Name.Equals("Movie"));
                            return(CommonQueryBuilder.Root(entitySet));
                        },
                    }
                },
                Parameters =
                {
                    new FunctionParameter("arg1", EdmDataTypes.Int32.NotNullable()),
                    new FunctionParameter("arg2", EdmDataTypes.String().NotNullable()),
                },
            });
        }
Example #21
0
 /// <summary>
 /// Constructs a root query expression for the given set
 /// </summary>
 /// <param name="entitySet">The entity set to build the root query for</param>
 /// <returns>A root query expression for the given set</returns>
 protected internal QueryExpression BuildRootQueryForSet(EntitySet entitySet)
 {
     return(CommonQueryBuilder.Root(entitySet.Name, this.Repository.RootDataTypes[entitySet.Name].CreateCollectionType()));
 }
Example #22
0
        private QueryExpression BuildQueryFromSegments()
        {
            var             segments         = this.currentUri.Segments;
            EntitySet       currentEntitySet = null;
            QueryExpression query            = null;

            foreach (var segment in segments)
            {
                if (segment.SegmentType == ODataUriSegmentType.ServiceRoot || segment == SystemSegment.Count || segment == SystemSegment.EntityReferenceLinks || segment == SystemSegment.Value)
                {
                    continue;
                }
                else if (segment.SegmentType == ODataUriSegmentType.EntitySet)
                {
                    // must be the root query
                    ExceptionUtilities.Assert(query == null, "Cannot have multiple entity set segments in the uri");

                    var entitySetSegment = (EntitySetSegment)segment;
                    query            = CommonQueryBuilder.Root(entitySetSegment.EntitySet.Name, this.Repository.RootDataTypes[entitySetSegment.EntitySet.Name].CreateCollectionType());
                    currentEntitySet = entitySetSegment.EntitySet;
                }
                else if (segment.SegmentType == ODataUriSegmentType.Key)
                {
                    // build the key expression
                    ExceptionUtilities.CheckObjectNotNull(query, "Key expression present in uri before any root segment");
                    var keySegment = (KeyExpressionSegment)segment;
                    var values     = keySegment.IncludedValues.Select(p => new NamedValue(p.Key.Name, p.Value));
                    query = query.Key(values);

                    this.shouldLastSegmentBeSingleton = true;
                }
                else if (segment.SegmentType == ODataUriSegmentType.NavigationProperty)
                {
                    ExceptionUtilities.CheckObjectNotNull(query, "Navigation property present in uri before any root segment");

                    var navigationSegment = (NavigationSegment)segment;
                    query = query.Property(navigationSegment.NavigationProperty.Name);

                    ExceptionUtilities.CheckObjectNotNull(currentEntitySet, "Expected an EntitySet Segment prior to a NavigationSegment");
                    currentEntitySet = currentEntitySet.GetRelatedEntitySet(navigationSegment.NavigationProperty);

                    this.shouldLastSegmentBeSingleton = false;
                }
                else if (segment.SegmentType == ODataUriSegmentType.NamedStream)
                {
                    var namedStreamSegment = (NamedStreamSegment)segment;
                    query = query.Property(namedStreamSegment.Name);

                    this.shouldLastSegmentBeSingleton = false;
                }
                else if (segment.SegmentType == ODataUriSegmentType.EntityType)
                {
                    query = this.AddEntityTypeFilter(currentEntitySet, query, (EntityTypeSegment)segment);
                }
                else if (segment.SegmentType == ODataUriSegmentType.Function)
                {
                    ExceptionUtilities.Assert(query == null, "Cannot have multiple root query segments in the uri");

                    var      serviceOperationSegment = (FunctionSegment)segment;
                    Function serviceOperation        = serviceOperationSegment.Function;
                    var      bodyAnnotation          = serviceOperation.Annotations.OfType <FunctionBodyAnnotation>().SingleOrDefault();
                    ExceptionUtilities.CheckObjectNotNull(bodyAnnotation, "Cannot evaluate function without body annotation");

                    List <QueryExpression> serviceOpArguments = new List <QueryExpression>();
                    foreach (var parameter in serviceOperation.Parameters)
                    {
                        var parameterPrimitiveType = parameter.DataType as PrimitiveDataType;
                        ExceptionUtilities.CheckObjectNotNull(parameterPrimitiveType, "Non primitive parameter types are unsupported");

                        string parameterValue;
                        if (this.currentUri.CustomQueryOptions.TryGetValue(parameter.Name, out parameterValue))
                        {
                            object argValue = this.LiteralConverter.DeserializePrimitive(parameterValue, parameterPrimitiveType.GetFacetValue <PrimitiveClrTypeFacet, Type>(typeof(object)));
                            serviceOpArguments.Add(CommonQueryBuilder.Constant(argValue));
                        }
                        else
                        {
                            serviceOpArguments.Add(CommonQueryBuilder.Null(this.Repository.TypeLibrary.GetDefaultQueryType(parameterPrimitiveType)));
                        }
                    }

                    query = new QueryCustomFunctionCallExpression(
                        this.Repository.TypeLibrary.GetDefaultQueryType(serviceOperation.ReturnType),
                        serviceOperation,
                        bodyAnnotation.FunctionBody,
                        false,
                        false,
                        serviceOpArguments.ToArray());

                    serviceOperation.TryGetExpectedServiceOperationEntitySet(out currentEntitySet);
                }
                else
                {
                    // must be a property segment
                    var propertySegment = segment as PropertySegment;
                    ExceptionUtilities.CheckObjectNotNull(propertySegment, "Uri segments contained unhandled segment type '{0}'", segment.SegmentType);
                    ExceptionUtilities.CheckObjectNotNull(query, "Property present in uri before any root segment");

                    query = query.Property(propertySegment.Property.Name);

                    this.shouldLastSegmentBeSingleton = false;
                }
            }

            return(query);
        }