public ODataSingletonDeserializerTest()
        {
            EdmModel model = new EdmModel();
            var employeeType = new EdmEntityType("NS", "Employee");
            employeeType.AddStructuralProperty("EmployeeId", EdmPrimitiveTypeKind.Int32);
            employeeType.AddStructuralProperty("EmployeeName", EdmPrimitiveTypeKind.String);
            model.AddElement(employeeType);

            EdmEntityContainer defaultContainer = new EdmEntityContainer("NS", "Default");
            model.AddElement(defaultContainer);

            _singleton = new EdmSingleton(defaultContainer, "CEO", employeeType);
            defaultContainer.AddElement(_singleton);

            model.SetAnnotationValue<ClrTypeAnnotation>(employeeType, new ClrTypeAnnotation(typeof(EmployeeModel)));

            _edmModel = model;
            _edmContainer = defaultContainer;

            _readContext = new ODataDeserializerContext
            {
                Path = new ODataPath(new SingletonPathSegment(_singleton)),
                Model = _edmModel,
                ResourceType = typeof(EmployeeModel)
            }; 

            _deserializerProvider = new DefaultODataDeserializerProvider();
        }
        public static IEdmModel GetEdmModel()
        {
            EdmModel model = new EdmModel();

            // Create and add product entity type.
            EdmEntityType product = new EdmEntityType("NS", "Product");
            product.AddKeys(product.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32));
            product.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
            product.AddStructuralProperty("Price", EdmPrimitiveTypeKind.Double);
            model.AddElement(product);

            // Create and add category entity type.
            EdmEntityType category = new EdmEntityType("NS", "Category");
            category.AddKeys(category.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32));
            category.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
            model.AddElement(category);

            // Set navigation from product to category.
            EdmNavigationPropertyInfo propertyInfo = new EdmNavigationPropertyInfo();
            propertyInfo.Name = "Category";
            propertyInfo.TargetMultiplicity = EdmMultiplicity.One;
            propertyInfo.Target = category;
            EdmNavigationProperty productCategory = product.AddUnidirectionalNavigation(propertyInfo);

            // Create and add entity container.
            EdmEntityContainer container = new EdmEntityContainer("NS", "DefaultContainer");
            model.AddElement(container);

            // Create and add entity set for product and category.
            EdmEntitySet products = container.AddEntitySet("Products", product);
            EdmEntitySet categories = container.AddEntitySet("Categories", category);
            products.AddNavigationTarget(productCategory, categories);

            return model;
        }
        public NonPrimitiveTypeRoundtripAtomTests()
        {
            this.model = new EdmModel();

            EdmComplexType personalInfo = new EdmComplexType(MyNameSpace, "PersonalInfo");
            personalInfo.AddStructuralProperty("Age", EdmPrimitiveTypeKind.Int16);
            personalInfo.AddStructuralProperty("Email", EdmPrimitiveTypeKind.String);
            personalInfo.AddStructuralProperty("Tel", EdmPrimitiveTypeKind.String);
            personalInfo.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Guid);
            
            EdmComplexType subjectInfo = new EdmComplexType(MyNameSpace, "Subject");
            subjectInfo.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
            subjectInfo.AddStructuralProperty("Score", EdmPrimitiveTypeKind.Int16);

            EdmCollectionTypeReference subjectsCollection = new EdmCollectionTypeReference(new EdmCollectionType(new EdmComplexTypeReference(subjectInfo, isNullable:true)));

            EdmEntityType studentInfo = new EdmEntityType(MyNameSpace, "Student");
            studentInfo.AddStructuralProperty("Info", new EdmComplexTypeReference(personalInfo, isNullable: false));
            studentInfo.AddProperty(new EdmStructuralProperty(studentInfo, "Subjects", subjectsCollection));

            EdmCollectionTypeReference hobbiesCollection = new EdmCollectionTypeReference(new EdmCollectionType(EdmCoreModel.Instance.GetString(isNullable: false)));
            studentInfo.AddProperty(new EdmStructuralProperty(studentInfo, "Hobbies", hobbiesCollection));

            model.AddElement(studentInfo);
            model.AddElement(personalInfo);
            model.AddElement(subjectInfo);
        }
        public OperationImportSegmentUnitTests()
        {
            nullableIntType = new EdmPrimitiveTypeReference(EdmCoreModel.Instance.GetPrimitiveType(EdmPrimitiveTypeKind.Int32), true);
            nullableDecimalType = new EdmPrimitiveTypeReference(EdmCoreModel.Instance.GetPrimitiveType(EdmPrimitiveTypeKind.Decimal), true);
            nullableBinaryType = new EdmPrimitiveTypeReference(EdmCoreModel.Instance.GetPrimitiveType(EdmPrimitiveTypeKind.Binary), true);
            nullableStringType = new EdmPrimitiveTypeReference(EdmCoreModel.Instance.GetPrimitiveType(EdmPrimitiveTypeKind.String), true);

            container = ModelBuildingHelpers.BuildValidEntityContainer();
            model = new EdmModel();
            model.AddElement(container);

            this.functionIntToInt = new EdmFunction("Name.Space", "Function", this.nullableIntType);
            this.functionIntToInt.AddParameter("Parameter1", this.nullableIntType);
            this.functionImportIntToInt = new EdmFunctionImport(this.container, "Function", this.functionIntToInt);

            this.functionDecimalToInt = new EdmFunction("Name.Space", "Function", this.nullableIntType);
            this.functionDecimalToInt.AddParameter("Parameter1", this.nullableDecimalType);
            this.functionImportDecimalToInt = new EdmFunctionImport(this.container, "Function", this.functionDecimalToInt);

            this.functionBinaryToInt = new EdmFunction("Name.Space", "Function", this.nullableIntType);
            this.functionBinaryToInt.AddParameter("Parameter1", this.nullableBinaryType);
            this.functionImportBinaryToInt = new EdmFunctionImport(this.container, "Function", this.functionBinaryToInt);

            this.functionIntToString = new EdmFunction("Name.Space", "Function", this.nullableStringType);
            this.functionIntToString.AddParameter("Parameter1", this.nullableIntType);
            this.functionImportIntToString = new EdmFunctionImport(this.container, "Function", this.functionIntToString);

            model.AddElement(functionIntToInt);
            model.AddElement(functionDecimalToInt);
            model.AddElement(functionBinaryToInt);
            model.AddElement(functionIntToString);
        }
        public CraftModel()
        {
            model = new EdmModel();

            var address = new EdmComplexType("NS", "Address");
            model.AddElement(address);

            var mail = new EdmEntityType("NS", "Mail");
            var mailId = mail.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32);
            mail.AddKeys(mailId);
            model.AddElement(mail);

            var person = new EdmEntityType("NS", "Person");
            model.AddElement(person);
            var personId = person.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32);
            person.AddKeys(personId);

            person.AddStructuralProperty("Addr", new EdmComplexTypeReference(address, /*Nullable*/false));
            MailBox = person.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo()
            {
                ContainsTarget = true,
                Name = "Mails",
                TargetMultiplicity = EdmMultiplicity.Many,
                Target = mail,
            });


            var container = new EdmEntityContainer("NS", "DefaultContainer");
            model.AddElement(container);
            MyLogin = container.AddSingleton("MyLogin", person);
        }
        static ODataFeedAndEntryTypeContextTests()
        {
            Model = new EdmModel();
            EntitySetElementType = new EdmEntityType("ns", "Customer");
            ExpectedEntityType = new EdmEntityType("ns", "VipCustomer", EntitySetElementType);
            ActualEntityType = new EdmEntityType("ns", "DerivedVipCustomer", ExpectedEntityType);

            EdmEntityContainer defaultContainer = new EdmEntityContainer("ns", "DefaultContainer");
            Model.AddElement(defaultContainer);
            Model.AddVocabularyAnnotation(new EdmAnnotation(defaultContainer, UrlConventionsConstants.ConventionTerm, UrlConventionsConstants.KeyAsSegmentAnnotationValue));

            EntitySet = new EdmEntitySet(defaultContainer, "Customers", EntitySetElementType);
            Model.AddElement(EntitySetElementType);
            Model.AddElement(ExpectedEntityType);
            Model.AddElement(ActualEntityType);
            defaultContainer.AddElement(EntitySet);

            SerializationInfo = new ODataFeedAndEntrySerializationInfo { NavigationSourceName = "MyCustomers", NavigationSourceEntityTypeName = "ns.MyCustomer", ExpectedTypeName = "ns.MyVipCustomer" };
            SerializationInfoWithEdmUnknowEntitySet = new ODataFeedAndEntrySerializationInfo() { NavigationSourceName = null, NavigationSourceEntityTypeName = "ns.MyCustomer", ExpectedTypeName = "ns.MyVipCustomer", NavigationSourceKind = EdmNavigationSourceKind.UnknownEntitySet };
            TypeContextWithoutModel = ODataFeedAndEntryTypeContext.Create(SerializationInfo, navigationSource: null, navigationSourceEntityType: null, expectedEntityType: null, model: Model, throwIfMissingTypeInfo: true);
            TypeContextWithModel = ODataFeedAndEntryTypeContext.Create(/*serializationInfo*/null, EntitySet, EntitySetElementType, ExpectedEntityType, Model, throwIfMissingTypeInfo: true);
            TypeContextWithEdmUnknowEntitySet = ODataFeedAndEntryTypeContext.Create(SerializationInfoWithEdmUnknowEntitySet, navigationSource: null, navigationSourceEntityType: null, expectedEntityType: null, model: Model, throwIfMissingTypeInfo: true);
            BaseTypeContextThatThrows = ODataFeedAndEntryTypeContext.Create(serializationInfo: null, navigationSource: null, navigationSourceEntityType: null, expectedEntityType: null, model: Model, throwIfMissingTypeInfo: true);
            BaseTypeContextThatWillNotThrow = ODataFeedAndEntryTypeContext.Create(serializationInfo: null, navigationSource: null, navigationSourceEntityType: null, expectedEntityType: null, model: Model, throwIfMissingTypeInfo: false);
        }
Exemple #7
0
        private static void ReferentialConstraintDemo()
        {
            Console.WriteLine("ReferentialConstraintDemo");

            EdmModel model = new EdmModel();
            var customer = new EdmEntityType("ns", "Customer");
            model.AddElement(customer);
            var customerId = customer.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32, false);
            customer.AddKeys(customerId);
            var address = new EdmComplexType("ns", "Address");
            model.AddElement(address);
            var code = address.AddStructuralProperty("gid", EdmPrimitiveTypeKind.Guid);
            customer.AddStructuralProperty("addr", new EdmComplexTypeReference(address, true));

            var order = new EdmEntityType("ns", "Order");
            model.AddElement(order);
            var oId = order.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32, false);
            order.AddKeys(oId);

            var orderCustomerId = order.AddStructuralProperty("CustomerId", EdmPrimitiveTypeKind.Int32, false);

            var nav = new EdmNavigationPropertyInfo()
            {
                Name = "NavCustomer",
                Target = customer,
                TargetMultiplicity = EdmMultiplicity.One,
                DependentProperties = new[] { orderCustomerId },
                PrincipalProperties = new[] { customerId }
            };
            order.AddUnidirectionalNavigation(nav);

            ShowModel(model);
        }
        public void TestModelWithTypeDefinition()
        {
            var model = new EdmModel();

            var addressType = new EdmTypeDefinition("MyNS", "Address", EdmPrimitiveTypeKind.String);
            model.AddElement(addressType);

            var weightType = new EdmTypeDefinition("MyNS", "Weight", EdmPrimitiveTypeKind.Decimal);
            model.AddElement(weightType);

            var personType = new EdmEntityType("MyNS", "Person");

            var addressTypeReference = new EdmTypeDefinitionReference(addressType, false);
            personType.AddStructuralProperty("Address", addressTypeReference);
            addressTypeReference.Definition.Should().Be(addressType);
            addressTypeReference.IsNullable.Should().BeFalse();

            var weightTypeReference = new EdmTypeDefinitionReference(weightType, true);
            personType.AddStructuralProperty("Weight", weightTypeReference);
            weightTypeReference.Definition.Should().Be(weightType);
            weightTypeReference.IsNullable.Should().BeTrue();

            var personId = personType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32);
            personType.AddKeys(personId);
        }
Exemple #9
0
        private static void EnumMemberExpressionDemo()
        {
            Console.WriteLine("EnumMemberExpressionDemo");

            var model = new EdmModel();
            var personType = new EdmEntityType("TestNS", "Person");
            model.AddElement(personType);
            var pid = personType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32, false);
            personType.AddKeys(pid);
            personType.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
            var colorType = new EdmEnumType("TestNS2", "Color", true);
            model.AddElement(colorType);
            colorType.AddMember("Cyan", new EdmIntegerConstant(1));
            colorType.AddMember("Blue", new EdmIntegerConstant(2));
            var outColorTerm = new EdmTerm("TestNS", "OutColor", new EdmEnumTypeReference(colorType, true));
            model.AddElement(outColorTerm);
            var exp = new EdmEnumMemberExpression(
                new EdmEnumMember(colorType, "Blue", new EdmIntegerConstant(2))
            );

            var annotation = new EdmAnnotation(personType, outColorTerm, exp);
            annotation.SetSerializationLocation(model, EdmVocabularyAnnotationSerializationLocation.Inline);
            model.SetVocabularyAnnotation(annotation);

            ShowModel(model);

            var ann = model.FindVocabularyAnnotations<IEdmValueAnnotation>(personType, "TestNS.OutColor").First();
            var memberExp = (IEdmEnumMemberExpression)ann.Value;
            foreach (var member in memberExp.EnumMembers)
            {
                Console.WriteLine(member.Name);
            }
        }
        public void AmbiguousValueTermTest()
        {
            EdmModel model = new EdmModel();

            IEdmValueTerm term1 = new EdmTerm("Foo", "Bar", EdmPrimitiveTypeKind.Byte);
            IEdmValueTerm term2 = new EdmTerm("Foo",  "Bar", EdmPrimitiveTypeKind.Decimal);
            IEdmValueTerm term3 = new EdmTerm("Foo",  "Bar", EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.Double, false));

            Assert.AreEqual(EdmTermKind.Value, term1.TermKind, "EdmTermKind is correct.");

            model.AddElement(term1);
            Assert.AreEqual(term1, model.FindValueTerm("Foo.Bar"), "Correct item.");

            model.AddElement(term2);
            model.AddElement(term3);

            IEdmValueTerm ambiguous = model.FindValueTerm("Foo.Bar");
            Assert.IsTrue(ambiguous.IsBad(), "Ambiguous binding is bad");

            Assert.AreEqual(EdmSchemaElementKind.ValueTerm, ambiguous.SchemaElementKind, "Correct schema element kind.");
            Assert.AreEqual("Foo", ambiguous.Namespace, "Correct Namespace");
            Assert.AreEqual("Bar", ambiguous.Name, "Correct Name");
            Assert.AreEqual(EdmTermKind.Value, ambiguous.TermKind, "Correct term kind.");
            Assert.IsTrue(ambiguous.Type.IsBad(), "Type is bad.");
        }
        public void CreateAmbiguousBinding()
        {
            EdmModel model = new EdmModel();

            EdmComplexType c1 = new EdmComplexType("Ambiguous", "Binding");
            EdmComplexType c2 = new EdmComplexType("Ambiguous", "Binding");
            EdmComplexType c3 = new EdmComplexType("Ambiguous", "Binding");

            model.AddElement(c1);
            Assert.AreEqual(c1, model.FindType("Ambiguous.Binding"), "Single item resolved");

            model.AddElement(c2);
            model.AddElement(c3);

            IEdmNamedElement ambiguous = model.FindType("Ambiguous.Binding");
            Assert.IsTrue(ambiguous.IsBad(), "Ambiguous binding is bad");
            Assert.AreEqual(EdmErrorCode.BadAmbiguousElementBinding, ambiguous.Errors().First().ErrorCode, "Ambiguous");

            c1 = null;
            c2 = new EdmComplexType("Ambiguous", "Binding2");

            Assert.IsTrue
                            (
                                model.SchemaElements.OfType<IEdmComplexType>().Count() == 3 && model.SchemaElements.OfType<IEdmComplexType>().All(n => n.FullName() == "Ambiguous.Binding"),
                                "The model must be immutable."
                            );
        }
        public void GetModel(EdmModel model, EdmEntityContainer container)
        {
            EdmEntityType student = new EdmEntityType("ns", "Student");
            student.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
            EdmStructuralProperty key = student.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32);
            student.AddKeys(key);
            model.AddElement(student);
            EdmEntitySet students = container.AddEntitySet("Students", student);

            EdmEntityType school = new EdmEntityType("ns", "School");
            school.AddKeys(school.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32));
            school.AddStructuralProperty("CreatedDay", EdmPrimitiveTypeKind.DateTimeOffset);
            model.AddElement(school);
            EdmEntitySet schools = container.AddEntitySet("Schools", student);

            EdmNavigationProperty schoolNavProp = student.AddUnidirectionalNavigation(
                new EdmNavigationPropertyInfo
                {
                    Name = "School",
                    TargetMultiplicity = EdmMultiplicity.One,
                    Target = school
                });
            students.AddNavigationTarget(schoolNavProp, schools);

            _school = school;
        }
        public WriterTypeNameEndToEndTests()
        {
            var model = new EdmModel();
            var type = new EdmEntityType("TestModel", "TestEntity", /* baseType */ null, /* isAbstract */ false, /* isOpen */ true);
            var keyProperty = type.AddStructuralProperty("DeclaredInt16", EdmPrimitiveTypeKind.Int16);
            type.AddKeys(new[] { keyProperty });

            // Note: DerivedPrimitive is declared as a Geography, but its value below will be set to GeographyPoint, which is derived from Geography.
            type.AddStructuralProperty("DerivedPrimitive", EdmPrimitiveTypeKind.Geography);
            var container = new EdmEntityContainer("TestModel", "Container");
            var set = container.AddEntitySet("Set", type);
            model.AddElement(type);
            model.AddElement(container);

            var writerStream = new MemoryStream();
            this.settings = new ODataMessageWriterSettings();
            this.settings.SetServiceDocumentUri(ServiceDocumentUri);

            // Make the message writer and entry writer lazy so that individual tests can tweak the settings before the message writer is created.
            this.messageWriter = new Lazy<ODataMessageWriter>(() =>
                new ODataMessageWriter(
                    (IODataResponseMessage)new InMemoryMessage { Stream = writerStream },
                    this.settings,
                    model));

            var entryWriter = new Lazy<ODataWriter>(() => this.messageWriter.Value.CreateODataEntryWriter(set, type));

            var valueWithAnnotation = new ODataPrimitiveValue(45);
            valueWithAnnotation.SetAnnotation(new SerializationTypeNameAnnotation { TypeName = "TypeNameFromSTNA" });

            var propertiesToWrite = new List<ODataProperty>
            {
                new ODataProperty
                {
                    Name = "DeclaredInt16", Value = (Int16)42
                }, 
                new ODataProperty
                {
                    Name = "UndeclaredDecimal", Value = (Decimal)4.5
                }, 
                new ODataProperty
                {
                    // Note: value is more derived than the declared type.
                    Name = "DerivedPrimitive", Value = Microsoft.Spatial.GeographyPoint.Create(42, 45)
                },
                new ODataProperty()
                {
                    Name = "PropertyWithSTNA", Value = valueWithAnnotation
                }
            };

            this.writerOutput = new Lazy<string>(() =>
            {
                entryWriter.Value.WriteStart(new ODataEntry { Properties = propertiesToWrite });
                entryWriter.Value.WriteEnd();
                entryWriter.Value.Flush();
                writerStream.Seek(0, SeekOrigin.Begin);
                return new StreamReader(writerStream).ReadToEnd();
            });
        }
        static InstanceAnnotationsReaderIntegrationTests()
        {
            EdmModel modelTmp = new EdmModel();
            EntityType = new EdmEntityType("TestNamespace", "TestEntityType");
            modelTmp.AddElement(EntityType);

            var keyProperty = new EdmStructuralProperty(EntityType, "ID", EdmCoreModel.Instance.GetInt32(false));
            EntityType.AddKeys(new IEdmStructuralProperty[] { keyProperty });
            EntityType.AddProperty(keyProperty);
            var resourceNavigationProperty = EntityType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo { Name = "ResourceNavigationProperty", Target = EntityType, TargetMultiplicity = EdmMultiplicity.ZeroOrOne });
            var resourceSetNavigationProperty = EntityType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo { Name = "ResourceSetNavigationProperty", Target = EntityType, TargetMultiplicity = EdmMultiplicity.Many });

            var defaultContainer = new EdmEntityContainer("TestNamespace", "DefaultContainer_sub");
            modelTmp.AddElement(defaultContainer);
            EntitySet = new EdmEntitySet(defaultContainer, "TestEntitySet", EntityType);
            EntitySet.AddNavigationTarget(resourceNavigationProperty, EntitySet);
            EntitySet.AddNavigationTarget(resourceSetNavigationProperty, EntitySet);
            defaultContainer.AddElement(EntitySet);

            Singleton = new EdmSingleton(defaultContainer, "TestSingleton", EntityType);
            Singleton.AddNavigationTarget(resourceNavigationProperty, EntitySet);
            Singleton.AddNavigationTarget(resourceSetNavigationProperty, EntitySet);
            defaultContainer.AddElement(Singleton);

            ComplexType = new EdmComplexType("TestNamespace", "TestComplexType");
            ComplexType.AddProperty(new EdmStructuralProperty(ComplexType, "StringProperty", EdmCoreModel.Instance.GetString(false)));
            modelTmp.AddElement(ComplexType);

            Model = TestUtils.WrapReferencedModelsToMainModel("TestNamespace", "DefaultContainer", modelTmp);
        }
        private static ODataEntry CreateEntryWithKeyAsSegmentConvention(bool addAnnotation, bool? useKeyAsSegment)
        {
            var model = new EdmModel();
            var container = new EdmEntityContainer("Fake", "Container");
            model.AddElement(container);
            if (addAnnotation)
            {
                model.AddVocabularyAnnotation(new EdmAnnotation(container, UrlConventionsConstants.ConventionTerm, UrlConventionsConstants.KeyAsSegmentAnnotationValue));                
            }
            
            EdmEntityType entityType = new EdmEntityType("Fake", "FakeType");
            entityType.AddKeys(entityType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32));
            model.AddElement(entityType);

            var entitySet = new EdmEntitySet(container, "FakeSet", entityType);
            container.AddElement(entitySet);

            var metadataContext = new ODataMetadataContext(
                true,
                ODataReaderBehavior.DefaultBehavior.OperationsBoundToEntityTypeMustBeContainerQualified,
                new EdmTypeReaderResolver(model, ODataReaderBehavior.DefaultBehavior),
                model,
                new Uri("http://temp.org/$metadata"),
                null /*requestUri*/);

            var thing = new ODataEntry {Properties = new[] {new ODataProperty {Name = "Id", Value = 1}}};
            thing.SetAnnotation(new ODataTypeAnnotation(entitySet, entityType));
            thing.MetadataBuilder = metadataContext.GetEntityMetadataBuilderForReader(new TestJsonLightReaderEntryState { Entry = thing, SelectedProperties = new SelectedPropertiesNode("*")}, useKeyAsSegment);
            return thing;
        }
        public static IEdmModel GetEdmModel()
        {
            if (_edmModel != null)
            {
                return _edmModel;
            }

            EdmModel model = new EdmModel();

            // entity type 'Customer' with single alternate keys
            EdmEntityType customer = new EdmEntityType("NS", "Customer");
            customer.AddKeys(customer.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32));
            customer.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
            var ssn = customer.AddStructuralProperty("SSN", EdmPrimitiveTypeKind.String);
            model.AddAlternateKeyAnnotation(customer, new Dictionary<string, IEdmProperty>
            {
                {"SSN", ssn}
            });
            model.AddElement(customer);

            // entity type 'Order' with multiple alternate keys
            EdmEntityType order = new EdmEntityType("NS", "Order");
            order.AddKeys(order.AddStructuralProperty("OrderId", EdmPrimitiveTypeKind.Int32));
            var orderName = order.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
            var orderToken = order.AddStructuralProperty("Token", EdmPrimitiveTypeKind.Guid);
            order.AddStructuralProperty("Amount", EdmPrimitiveTypeKind.Int32);
            model.AddAlternateKeyAnnotation(order, new Dictionary<string, IEdmProperty>
            {
                {"Name", orderName}
            });

            model.AddAlternateKeyAnnotation(order, new Dictionary<string, IEdmProperty>
            {
                {"Token", orderToken}
            });

            model.AddElement(order);

            // entity type 'Person' with composed alternate keys
            EdmEntityType person = new EdmEntityType("NS", "Person");
            person.AddKeys(person.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32));
            var country = person.AddStructuralProperty("Country", EdmPrimitiveTypeKind.String);
            var passport = person.AddStructuralProperty("Passport", EdmPrimitiveTypeKind.String);
            model.AddAlternateKeyAnnotation(person, new Dictionary<string, IEdmProperty>
            {
                {"Country", country},
                {"Passport", passport}
            });
            model.AddElement(person);

            // entity sets
            EdmEntityContainer container = new EdmEntityContainer("NS", "Default");
            model.AddElement(container);
            container.AddEntitySet("Customers", customer);
            container.AddEntitySet("Orders", order);
            container.AddEntitySet("People", person);

            return _edmModel = model;
        }
        public void ComplexValueTest()
        {
            EdmModel model = new EdmModel();

            var emptyComplexType = new EdmComplexType(DefaultNamespaceName, "EmptyComplexType");
            model.AddElement(emptyComplexType);

            var complexTypeWithStringProperty = new EdmComplexType(DefaultNamespaceName, "ComplexTypeWithStringProperty");
            complexTypeWithStringProperty.AddStructuralProperty("stringProperty", EdmCoreModel.Instance.GetString(isNullable: true));
            complexTypeWithStringProperty.AddStructuralProperty("numberProperty", EdmCoreModel.Instance.GetInt32(isNullable: false));
            model.AddElement(complexTypeWithStringProperty);

            model.Fixup();
            

            IEnumerable<PayloadReaderTestDescriptor> testDescriptors = new[]
            {
                // Empty element is a valid complex value
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.ComplexValue("TestModel.EmptyComplexType")
                        .XmlValueRepresentation(new XNode[0])
                        .WithTypeAnnotation(emptyComplexType),
                    PayloadEdmModel = model
                },
            };

            testDescriptors = testDescriptors.Concat(
                PropertiesElementAtomValues.CreatePropertiesElementPaddingPayloads<ComplexInstance>(
                    new PayloadReaderTestDescriptor(this.Settings)
                    {
                        PayloadElement = PayloadBuilder.ComplexValue("TestModel.ComplexTypeWithStringProperty")
                            .WithTypeAnnotation(complexTypeWithStringProperty),
                        PayloadEdmModel = model
                    },
                    (complexInstance, xmlValue) => complexInstance.XmlValueRepresentation(xmlValue)));

            testDescriptors = testDescriptors.Select(td => td.InProperty());

            testDescriptors = testDescriptors.Concat(new []
            {
                // Top-level property without expected type and no type name - this is read as primitive string!
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Property(null, PayloadBuilder.PrimitiveValue(string.Empty))
                        .XmlRepresentation("<m:value/>"),
                    PayloadEdmModel = model,
                },
            });

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.ReaderTestConfigurationProvider.AtomFormatConfigurations,
                (testDescriptor, testConfiguration) =>
                {
                    testDescriptor.RunTest(testConfiguration);
                });
        }
        public static IEdmModel CreateServiceEdmModel(string ns)
        {
            EdmModel model = new EdmModel();
            var defaultContainer = new EdmEntityContainer(ns, "PerfInMemoryContainer");
            model.AddElement(defaultContainer);

            var personType = new EdmEntityType(ns, "Person");
            var personIdProperty = new EdmStructuralProperty(personType, "PersonID", EdmCoreModel.Instance.GetInt32(false));
            personType.AddProperty(personIdProperty);
            personType.AddKeys(new IEdmStructuralProperty[] { personIdProperty });
            personType.AddProperty(new EdmStructuralProperty(personType, "FirstName", EdmCoreModel.Instance.GetString(false)));
            personType.AddProperty(new EdmStructuralProperty(personType, "LastName", EdmCoreModel.Instance.GetString(false)));
            personType.AddProperty(new EdmStructuralProperty(personType, "MiddleName", EdmCoreModel.Instance.GetString(true)));
            personType.AddProperty(new EdmStructuralProperty(personType, "Age", EdmCoreModel.Instance.GetInt32(false)));
            model.AddElement(personType);

            var simplePersonSet = new EdmEntitySet(defaultContainer, "SimplePeopleSet", personType);
            defaultContainer.AddElement(simplePersonSet);

            var largetPersonSet = new EdmEntitySet(defaultContainer, "LargePeopleSet", personType);
            defaultContainer.AddElement(largetPersonSet);

            var addressType = new EdmComplexType(ns, "Address");
            addressType.AddProperty(new EdmStructuralProperty(addressType, "Street", EdmCoreModel.Instance.GetString(false)));
            addressType.AddProperty(new EdmStructuralProperty(addressType, "City", EdmCoreModel.Instance.GetString(false)));
            addressType.AddProperty(new EdmStructuralProperty(addressType, "PostalCode", EdmCoreModel.Instance.GetString(false)));
            model.AddElement(addressType);

            var companyType = new EdmEntityType(ns, "Company");
            var companyId = new EdmStructuralProperty(companyType, "CompanyID", EdmCoreModel.Instance.GetInt32(false));
            companyType.AddProperty(companyId);
            companyType.AddKeys(companyId);
            companyType.AddProperty(new EdmStructuralProperty(companyType, "Name", EdmCoreModel.Instance.GetString(true)));
            companyType.AddProperty(new EdmStructuralProperty(companyType, "Address", new EdmComplexTypeReference(addressType, true)));
            companyType.AddProperty(new EdmStructuralProperty(companyType, "Revenue", EdmCoreModel.Instance.GetInt32(false)));

            model.AddElement(companyType);

            var companySet = new EdmEntitySet(defaultContainer, "CompanySet", companyType);
            defaultContainer.AddElement(companySet);

            var companyEmployeeNavigation = companyType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo()
            {
                Name = "Employees",
                Target = personType,
                TargetMultiplicity = EdmMultiplicity.Many
            });
            companySet.AddNavigationTarget(companyEmployeeNavigation, largetPersonSet);

            // ResetDataSource
            var resetDataSourceAction = new EdmAction(ns, "ResetDataSource", null, false, null);
            model.AddElement(resetDataSourceAction);
            defaultContainer.AddActionImport(resetDataSourceAction);

            return model;
        }
        public static IEdmModel CreateModel(string ns)
        {
            EdmModel model = new EdmModel();
            var defaultContainer = new EdmEntityContainer(ns, "DefaultContainer");
            model.AddElement(defaultContainer);

            var addressType = new EdmComplexType(ns, "Address");
            addressType.AddProperty(new EdmStructuralProperty(addressType, "Road", EdmCoreModel.Instance.GetString(false)));
            addressType.AddProperty(new EdmStructuralProperty(addressType, "City", EdmCoreModel.Instance.GetString(false)));
            model.AddElement(addressType);

            var personType = new EdmEntityType(ns, "Person");
            var personIdProperty = new EdmStructuralProperty(personType, "PersonId", EdmCoreModel.Instance.GetInt32(false));
            personType.AddProperty(personIdProperty);
            personType.AddKeys(new IEdmStructuralProperty[] { personIdProperty });
            personType.AddProperty(new EdmStructuralProperty(personType, "FirstName", EdmCoreModel.Instance.GetString(false)));
            personType.AddProperty(new EdmStructuralProperty(personType, "LastName", EdmCoreModel.Instance.GetString(false)));
            personType.AddProperty(new EdmStructuralProperty(personType, "Address", new EdmComplexTypeReference(addressType, true)));
            personType.AddProperty(new EdmStructuralProperty(personType, "Descriptions", new EdmCollectionTypeReference(new EdmCollectionType(EdmCoreModel.Instance.GetString(false)))));

            model.AddElement(personType);
            var peopleSet = new EdmEntitySet(defaultContainer, "People", personType);
            defaultContainer.AddElement(peopleSet);

            var numberComboType = new EdmComplexType(ns, "NumberCombo");
            numberComboType.AddProperty(new EdmStructuralProperty(numberComboType, "Small", EdmCoreModel.Instance.GetInt32(false)));
            numberComboType.AddProperty(new EdmStructuralProperty(numberComboType, "Middle", EdmCoreModel.Instance.GetInt64(false)));
            numberComboType.AddProperty(new EdmStructuralProperty(numberComboType, "Large", EdmCoreModel.Instance.GetDecimal(false)));
            model.AddElement(numberComboType);

            var productType = new EdmEntityType(ns, "Product");
            var productIdProperty = new EdmStructuralProperty(productType, "ProductId", EdmCoreModel.Instance.GetInt32(false));
            productType.AddProperty(productIdProperty);
            productType.AddKeys(new IEdmStructuralProperty[] { productIdProperty });
            productType.AddProperty(new EdmStructuralProperty(productType, "Quantity", EdmCoreModel.Instance.GetInt64(false)));
            productType.AddProperty(new EdmStructuralProperty(productType, "LifeTimeInSeconds", EdmCoreModel.Instance.GetDecimal(false)));
            productType.AddProperty(new EdmStructuralProperty(productType, "TheCombo", new EdmComplexTypeReference(numberComboType, true)));
            productType.AddProperty(new EdmStructuralProperty(productType, "LargeNumbers", new EdmCollectionTypeReference(new EdmCollectionType(EdmCoreModel.Instance.GetDecimal(false)))));

            model.AddElement(productType);
            var productsSet = new EdmEntitySet(defaultContainer, "Products", productType);
            defaultContainer.AddElement(productsSet);

            var productsProperty = personType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo
            {
                Name = "Products",
                Target = productType,
                TargetMultiplicity = EdmMultiplicity.Many
            });
            peopleSet.AddNavigationTarget(productsProperty, productsSet);

            IEnumerable<EdmError> errors;
            model.Validate(out errors);

            return model;
        }
Exemple #20
0
 public Task<IEdmModel> GetModelAsync(InvocationContext context, CancellationToken cancellationToken)
 {
     var model = new EdmModel();
     var dummyType = new EdmEntityType("NS", "Dummy");
     model.AddElement(dummyType);
     var container = new EdmEntityContainer("NS", "DefaultContainer");
     container.AddEntitySet("Test", dummyType);
     model.AddElement(container);
     return Task.FromResult((IEdmModel)model);
 }
        public AutoGeneratedUrlsShouldPutKeyValueInDedicatedSegmentTests()
        {
            this.model = new EdmModel();
            this.entityContainer = new EdmEntityContainer("Namespace", "Container");

            this.personType = new EdmEntityType("Namespace", "Person");
            this.personType.AddKeys(this.personType.AddStructuralProperty("Key", EdmPrimitiveTypeKind.String));
            this.peopleSet = this.entityContainer.AddEntitySet("People", personType);
            model.AddElement(this.entityContainer);
            model.AddElement(this.personType);
        }
        public void Initialize()
        {
            this.model = new EdmModel();
            this.entityContainer = new EdmEntityContainer("Namespace", "Container");

            this.personType = new EdmEntityType("Namespace", "Person");
            this.personType.AddKeys(this.personType.AddStructuralProperty("Key", EdmPrimitiveTypeKind.String));
            this.peopleSet = this.entityContainer.AddEntitySet("People", personType);
            model.AddElement(this.entityContainer);
            model.AddElement(this.personType);
        }
        static ODataAtomWriterIntegrationTests()
        {
            Model = new EdmModel();
            EntityType = new EdmEntityType("Namespace", "EntityType");

            Model.AddElement(EntityType);
            var entityContainer = new EdmEntityContainer("Namespace", "Container");
            EntitySet = entityContainer.AddEntitySet("EntitySet", EntityType);
            Model.AddElement(entityContainer);
            Model.Fixup();
        }
        public void DuplicateFunctionOverloadsWithDifferentBindingTypesAndSameNameWithDifferentReturnTypesShouldNotError()
        {
            var edmFunction = new EdmFunction("n.s", "GetStuff", EdmCoreModel.Instance.GetString(true), true /*isBound*/, null /*entitySetPath*/, false /*isComposable*/);
            edmFunction.AddParameter("bindingParameter", EdmCoreModel.Instance.GetInt16(true));
            var edmFunction2 = new EdmFunction("n.s", "GetStuff", EdmCoreModel.Instance.GetInt16(true), true /*isBound*/, null /*entitySetPath*/, false /*isComposable*/);
            edmFunction2.AddParameter("bindingParameter", EdmCoreModel.Instance.GetInt32(true));

            EdmModel model = new EdmModel();
            model.AddElement(edmFunction);
            model.AddElement(edmFunction2);
            ValidateNoError(model);
        }
        public void DuplicateUnBoundFunctionOverloadsSameParameterNamesShouldError()
        {
            var edmFunction = new EdmFunction("n.s", "GetStuff", EdmCoreModel.Instance.GetString(true), false /*isBound*/, null /*entitySetPath*/, false /*isComposable*/);
            edmFunction.AddParameter("bindingParameter1", EdmCoreModel.Instance.GetInt16(true));
            var edmFunction2 = new EdmFunction("n.s", "GetStuff", EdmCoreModel.Instance.GetInt16(true), false /*isBound*/, null /*entitySetPath*/, false /*isComposable*/);
            edmFunction2.AddParameter("bindingParameter1", EdmCoreModel.Instance.GetInt32(true));

            EdmModel model = new EdmModel();
            model.AddElement(edmFunction);
            model.AddElement(edmFunction2);
            ValidateError(model, EdmErrorCode.DuplicateFunctions, Strings.EdmModel_Validator_Semantic_ModelDuplicateUnBoundFunctionsParameterNames("n.s.GetStuff"));
        }
        public ODataJsonLightReaderEnumIntegrationTests()
        {
            EdmModel tmpModel = new EdmModel();

            // enum without flags
            var enumType = new EdmEnumType("NS", "Color");
            var red = new EdmEnumMember(enumType, "Red", new EdmIntegerConstant(1));
            enumType.AddMember(red);
            enumType.AddMember("Green", new EdmIntegerConstant(2));
            enumType.AddMember("Blue", new EdmIntegerConstant(3));
            tmpModel.AddElement(enumType);

            // enum with flags
            var enumFlagsType = new EdmEnumType("NS", "ColorFlags", isFlags: true);
            enumFlagsType.AddMember("Red", new EdmIntegerConstant(1));
            enumFlagsType.AddMember("Green", new EdmIntegerConstant(2));
            enumFlagsType.AddMember("Blue", new EdmIntegerConstant(4));
            tmpModel.AddElement(enumFlagsType);

            this.entityType = new EdmEntityType("NS", "MyEntityType", isAbstract: false, isOpen: true, baseType: null);
            EdmStructuralProperty floatId = new EdmStructuralProperty(this.entityType, "FloatId", EdmCoreModel.Instance.GetSingle(false));
            this.entityType.AddKeys(floatId);
            this.entityType.AddProperty(floatId);
            var enumTypeReference = new EdmEnumTypeReference(enumType, true);
            this.entityType.AddProperty(new EdmStructuralProperty(this.entityType, "Color", enumTypeReference));
            var enumFlagsTypeReference = new EdmEnumTypeReference(enumFlagsType, false);
            this.entityType.AddProperty(new EdmStructuralProperty(this.entityType, "ColorFlags", enumFlagsTypeReference));

            // enum in complex type
            EdmComplexType myComplexType = new EdmComplexType("NS", "MyComplexType");
            myComplexType.AddProperty(new EdmStructuralProperty(myComplexType, "MyColorFlags", enumFlagsTypeReference));
            myComplexType.AddProperty(new EdmStructuralProperty(myComplexType, "Height", EdmCoreModel.Instance.GetDouble(false)));
            tmpModel.AddElement(myComplexType);
            this.entityType.AddProperty(new EdmStructuralProperty(this.entityType, "MyComplexType", new EdmComplexTypeReference(myComplexType, true)));

            // enum in derived complex type
            EdmComplexType myDerivedComplexType = new EdmComplexType("NS", "MyDerivedComplexType", myComplexType, false);
            myDerivedComplexType.AddProperty(new EdmStructuralProperty(myDerivedComplexType, "MyDerivedColorFlags", new EdmEnumTypeReference(enumFlagsType, false)));
            tmpModel.AddElement(myDerivedComplexType);
            
            // enum in collection type
            EdmCollectionType myCollectionType = new EdmCollectionType(enumFlagsTypeReference);
            this.entityType.AddProperty(new EdmStructuralProperty(this.entityType, "MyCollectionType", new EdmCollectionTypeReference(myCollectionType)));

            tmpModel.AddElement(this.entityType);

            var defaultContainer = new EdmEntityContainer("NS", "DefaultContainer_sub");
            this.entitySet = new EdmEntitySet(defaultContainer, "MySet", this.entityType);
            defaultContainer.AddEntitySet(this.entitySet.Name, this.entityType);
            tmpModel.AddElement(defaultContainer);

            this.userModel = TestUtils.WrapReferencedModelsToMainModel("NS", "DefaultContainer", tmpModel);
        }
 public void Initialize()
 {
     EdmModel tmp = new EdmModel();
     this.type = new EdmEntityType("Namespace", "Type");
     this.type.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo() { Target = this.type, TargetMultiplicity = EdmMultiplicity.Many, Name = "NavProp" });
     this.type.AddProperty(new EdmStructuralProperty(this.type, "PrimitiveProp", EdmCoreModel.Instance.GetInt32(false)));
     tmp.AddElement(this.type);
     EdmEntityContainer edmEntityContainer = new EdmEntityContainer("Namespace", "Container_sub");
     this.entitySet = edmEntityContainer.AddEntitySet("EntitySet", this.type);
     tmp.AddElement(edmEntityContainer);
     this.model = TestUtils.WrapReferencedModelsToMainModel("Namespace", "Container", tmp);
 }
 private static EdmModel CreateTestModel()
 {
     var objectType = new EdmEntityType("DefaultNamespace", "Object");
     var personType = new EdmEntityType("DefaultNamespace", "Person", objectType);
     var container = new EdmEntityContainer("DefaultNamespace", "Container");
     container.AddEntitySet("Objects", objectType);
     container.AddEntitySet("People", personType);
     var model = new EdmModel();
     model.AddElement(objectType);
     model.AddElement(personType);
     model.AddElement(container);
     return model;
 }
            public Task<IEdmModel> GetModelAsync(InvocationContext context, CancellationToken cancellationToken)
            {
                var model = new EdmModel();
                var entityType = new EdmEntityType(
                    "TestNamespace", "TestName");
                var entityContainer = new EdmEntityContainer(
                    "TestNamespace", "Entities");
                entityContainer.AddEntitySet("TestEntitySet", entityType);
                model.AddElement(entityType);
                model.AddElement(entityContainer);

                return Task.FromResult<IEdmModel>(model);
            }
        static ExapndOptionFunctionalTests()
        {
            string namespaceA = "NS";
            EdmModel edmModel = new EdmModel();
            EdmEntityType type1 = new EdmEntityType(namespaceA, "T1");
            EdmEntityType type2 = new EdmEntityType(namespaceA, "T2", type1);
            EdmEntityType type3 = new EdmEntityType(namespaceA, "T3", type2);
            EdmNavigationProperty nav21 = type2.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo()
            {
                Name = "Nav21",
                ContainsTarget = false,
                Target = type1,
                TargetMultiplicity = EdmMultiplicity.ZeroOrOne,
            });

            EdmNavigationProperty nav22 = type2.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo()
            {
                Name = "Nav22",
                ContainsTarget = false,
                Target = type2,
                TargetMultiplicity = EdmMultiplicity.One,
            });

            EdmNavigationProperty nav23 = type2.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo()
            {
                Name = "Nav23",
                ContainsTarget = false,
                Target = type3,
                TargetMultiplicity = EdmMultiplicity.Many,
            });

            
            edmModel.AddElement(type1);
            edmModel.AddElement(type2);
            edmModel.AddElement(type3);

            EdmEntityContainer container = new EdmEntityContainer(namespaceA, "Con1");
            var set1 = container.AddEntitySet(namespaceA, type1);
            var set2 = container.AddEntitySet(namespaceA, type2);
            var set3 = container.AddEntitySet(namespaceA, type3);
            edmModel.AddElement(container);
            set2.AddNavigationTarget(nav21, set1);
            set2.AddNavigationTarget(nav22, set2);
            set2.AddNavigationTarget(nav23, set3);

            Model = edmModel;
            T2Type = type2;
            T3Type = type3;
            T2Set = set2;
            T3Set = set3;
        }
Exemple #31
0
        /// <summary>
        /// Asynchronously produces a base model.
        /// </summary>
        /// <param name="context">
        /// The model context.
        /// </param>
        /// <param name="cancellationToken">
        /// A cancellation token.
        /// </param>
        /// <returns>
        /// A task that represents the asynchronous
        /// operation whose result is the base model.
        /// </returns>
        public Task <IEdmModel> GetModelAsync(
            InvocationContext context,
            CancellationToken cancellationToken)
        {
            Ensure.NotNull(context, "context");

            var    model         = new EdmModel();
            var    dbContext     = context.GetApiService <DbContext>();
            var    elementMap    = new Dictionary <IAnnotatable, IEdmElement>();
            var    entityTypes   = dbContext.Model.GetEntityTypes();
            string namespaceName = CalcNamespace(dbContext, entityTypes);

            var entityContainer = new EdmEntityContainer(
                namespaceName, "Container");
            Dictionary <Type, PropertyInfo> dbSetProperties = GetDbSetPropeties(dbContext);

            // TODO GitHubIssue#36 : support complex and entity inheritance
            foreach (var efEntityType in entityTypes)
            {
                if (elementMap.ContainsKey(efEntityType))
                {
                    continue;
                }

                List <EdmStructuralProperty> concurrencyProperties;
                var entityType = ModelProducer.CreateEntityType(
                    efEntityType, model, out concurrencyProperties);
                model.AddElement(entityType);

                PropertyInfo propInfo;
                if (dbSetProperties.TryGetValue(efEntityType.ClrType, out propInfo))
                {
                    var entitySet = entityContainer.AddEntitySet(propInfo.Name, entityType);
                    if (concurrencyProperties != null)
                    {
                        model.SetOptimisticConcurrencyAnnotation(entitySet, concurrencyProperties);
                    }
                }

                elementMap.Add(efEntityType, entityType);
            }

            CreateNavigations(entityContainer, entityTypes, elementMap);

            // TODO GitHubIssue#36 : support function imports
            model.AddElement(entityContainer);

            return(Task.FromResult <IEdmModel>(model));
        }
Exemple #32
0
        private static IEdmEnumTypeReference GetEnumTypeReference(
            EdmProperty efProperty,
            EdmModel model,
            IDictionary <MetadataItem, IEdmElement> elementMap)
        {
            var         efEnumType = efProperty.EnumType;
            EdmEnumType enumType;
            IEdmElement element;

            if (elementMap.TryGetValue(efEnumType, out element))
            {
                enumType = (EdmEnumType)element;
            }
            else
            {
                enumType = new EdmEnumType(efEnumType.NamespaceName, efEnumType.Name);
                elementMap.Add(efEnumType, enumType);
                model.AddElement(enumType);

                foreach (var member in efEnumType.Members)
                {
                    var longValue = Convert.ToInt64(member.Value, CultureInfo.InvariantCulture);
                    enumType.AddMember(member.Name, new EdmIntegerConstant(longValue));
                }
            }

            return(new EdmEnumTypeReference(enumType, efProperty.Nullable));
        }
Exemple #33
0
        private static IEdmComplexTypeReference GetComplexTypeReference(
            EdmProperty efProperty,
            EdmModel model,
            IDictionary <MetadataItem, IEdmElement> elementMap)
        {
            var            efComplexType = efProperty.ComplexType;
            EdmComplexType complexType;
            IEdmElement    element;

            if (elementMap.TryGetValue(efComplexType, out element))
            {
                complexType = (EdmComplexType)element;
            }
            else
            {
                complexType = new EdmComplexType(efComplexType.NamespaceName, efComplexType.Name);
                elementMap.Add(efComplexType, complexType);
                model.AddElement(complexType);

                foreach (var property in efComplexType.Properties)
                {
                    var propertyTypeRef = GetTypeReference(property, model, elementMap);
                    if (propertyTypeRef != null)
                    {
                        complexType.AddStructuralProperty(property.Name, propertyTypeRef);
                    }
                }
            }

            return(new EdmComplexTypeReference(complexType, efProperty.Nullable));
        }
Exemple #34
0
        /// <summary>
        /// Asynchronously produces a base model.
        /// </summary>
        /// <param name="context">
        /// The model context.
        /// </param>
        /// <param name="cancellationToken">
        /// A cancellation token.
        /// </param>
        /// <returns>
        /// A task that represents the asynchronous
        /// operation whose result is the base model.
        /// </returns>
        public Task <IEdmModel> GetModelAsync(
            InvocationContext context,
            CancellationToken cancellationToken)
        {
            var model         = new EdmModel();
            var domainContext = context.ApiContext;
            var dbContext     = domainContext.GetApiService <DbContext>();
            var elementMap    = new Dictionary <IAnnotatable, IEdmElement>();
            var efModel       = dbContext.Model;
            var namespaceName = efModel.EntityTypes
                                .Select(t => t.HasClrType() ? t.ClrType.Namespace : null)
                                .Where(t => t != null)
                                .GroupBy(nameSpace => nameSpace)
                                .Select(group => new
            {
                NameSpace = group.Key,
                Count     = group.Count(),
            })
                                .OrderByDescending(nsItem => nsItem.Count)
                                .Select(nsItem => nsItem.NameSpace)
                                .FirstOrDefault();

            if (namespaceName == null)
            {
                // When dbContext has not a namespace, just use its type name as namespace.
                namespaceName = dbContext.GetType().Namespace ?? dbContext.GetType().Name;
            }

            var entityTypes     = efModel.EntityTypes;
            var entityContainer = new EdmEntityContainer(
                namespaceName, "Container");

            var dbSetProperties = dbContext.GetType()
                                  .GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)
                                  .Where(e => e.PropertyType.IsGenericType &&
                                         e.PropertyType.GetGenericTypeDefinition() == typeof(DbSet <>))
                                  .ToDictionary(e => e.PropertyType.GetGenericArguments()[0]);

            // TODO GitHubIssue#36 : support complex and entity inheritance
            foreach (var efEntityType in entityTypes)
            {
                if (elementMap.ContainsKey(efEntityType))
                {
                    continue;
                }

                List <EdmStructuralProperty> concurrencyProperties;
                var entityType = ModelProducer.CreateEntityType(
                    efModel, efEntityType, model, out concurrencyProperties);
                model.AddElement(entityType);
                elementMap.Add(efEntityType, entityType);

                System.Reflection.PropertyInfo propInfo;
                if (dbSetProperties.TryGetValue(efEntityType.ClrType, out propInfo))
                {
                    var entitySet = entityContainer.AddEntitySet(propInfo.Name, entityType);
                    if (concurrencyProperties != null)
                    {
                        model.SetOptimisticConcurrencyAnnotation(entitySet, concurrencyProperties);
                    }
                }
            }

            foreach (var efEntityType in entityTypes)
            {
                foreach (var navi in efEntityType.GetNavigations())
                {
                    ModelProducer.AddNavigationProperties(
                        efModel, navi, model, elementMap);
                    ModelProducer.AddNavigationPropertyBindings(
                        efModel, navi, entityContainer, elementMap);
                }
            }

            // TODO GitHubIssue#36 : support function imports
            model.AddElement(entityContainer);

            return(Task.FromResult <IEdmModel>(model));
        }
Exemple #35
0
        /// <summary>
        /// Asynchronously produces a base model.
        /// </summary>
        /// <param name="context">
        /// The model context.
        /// </param>
        /// <param name="cancellationToken">
        /// A cancellation token.
        /// </param>
        /// <returns>
        /// A task that represents the asynchronous
        /// operation whose result is the base model.
        /// </returns>
        public Task <EdmModel> ProduceModelAsync(
            ModelContext context,
            CancellationToken cancellationToken)
        {
            Ensure.NotNull(context);
            var model         = new EdmModel();
            var domainContext = context.DomainContext;
            var dbContext     = domainContext.GetProperty <DbContext>("DbContext");
            var elementMap    = new Dictionary <MetadataItem, IEdmElement>();
            var efModel       = (dbContext as IObjectContextAdapter)
                                .ObjectContext.MetadataWorkspace;
            var namespaceName = efModel.GetItems <EntityType>(DataSpace.CSpace)
                                .Select(t => efModel.GetObjectSpaceType(t).NamespaceName)
                                .GroupBy(nameSpace => nameSpace)
                                .Select(group => new
            {
                NameSpace = group.Key,
                Count     = group.Count(),
            })
                                .OrderByDescending(nsItem => nsItem.Count)
                                .Select(nsItem => nsItem.NameSpace)
                                .FirstOrDefault();

            if (namespaceName == null)
            {
                // When dbContext has not a namespace, just use its type name as namespace.
                namespaceName = dbContext.GetType().Namespace ?? dbContext.GetType().Name;
            }

            var efEntityContainer = efModel.GetItems <EntityContainer>(DataSpace.CSpace).Single();
            var entityContainer   = new EdmEntityContainer(namespaceName, efEntityContainer.Name);

            elementMap.Add(efEntityContainer, entityContainer);

            // TODO GitHubIssue#36 : support complex and enumeration types
            foreach (var efEntitySet in efEntityContainer.EntitySets)
            {
                var efEntityType = efEntitySet.ElementType;
                if (elementMap.ContainsKey(efEntityType))
                {
                    continue;
                }

                List <EdmStructuralProperty> concurrencyProperties;
                var entityType = CreateEntityType(efModel, efEntityType, model, elementMap, out concurrencyProperties);
                model.AddElement(entityType);
                elementMap.Add(efEntityType, entityType);
                var entitySet = entityContainer.AddEntitySet(efEntitySet.Name, entityType);
                if (concurrencyProperties != null)
                {
                    model.SetOptimisticConcurrencyAnnotation(entitySet, concurrencyProperties);
                }

                elementMap.Add(efEntitySet, entitySet);
            }

            foreach (var efAssociationSet in efEntityContainer.AssociationSets)
            {
                AddNavigationProperties(efAssociationSet, elementMap);
                AddNavigationPropertyBindings(efAssociationSet, elementMap);
            }

            // TODO GitHubIssue#36 : support function imports
            model.AddElement(entityContainer);

            return(Task.FromResult(model));
        }