private EdmEntityType ConvertToEdmEntityType(JSchema schema, EdmModel model, string name)
        {
            var type = new EdmEntityType("namespace", name);

            foreach (var property in schema.Properties)
            {
                if (property.Value.Type == null)
                    throw new Exception("Type specyfication missing.");

                var structuralType = MapPropertyToStructuralType(property, schema, model);

                if (structuralType != null)
                {
                    type.AddStructuralProperty(property.Key, structuralType);
                }
                else
                {
                    type.AddStructuralProperty(property.Key, ToEdmPrimitiveType(property.Value.Type.Value));
                }
            }

            model.AddElement(type);

            return type;
        }
        public static IEdmModel SimpleCustomerOrderModel()
        {
            var model = new EdmModel();
            var customerType = new EdmEntityType("Default", "Customer");
            customerType.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32);
            customerType.AddStructuralProperty("FirstName", EdmPrimitiveTypeKind.String);
            customerType.AddStructuralProperty("LastName", EdmPrimitiveTypeKind.String);
            IEdmTypeReference primitiveTypeReference = EdmCoreModel.Instance
                .GetPrimitive(EdmPrimitiveTypeKind.String, isNullable: true);
            customerType.AddStructuralProperty("City", primitiveTypeReference, defaultValue: null,
                concurrencyMode: EdmConcurrencyMode.Fixed);
            model.AddElement(customerType);

            var orderType = new EdmEntityType("Default", "Order");
            orderType.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32);
            orderType.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
            orderType.AddStructuralProperty("Shipment", EdmPrimitiveTypeKind.String);
            model.AddElement(orderType);

            var addressType = new EdmComplexType("Default", "Address");
            addressType.AddStructuralProperty("Street", EdmPrimitiveTypeKind.String);
            addressType.AddStructuralProperty("City", EdmPrimitiveTypeKind.String);
            addressType.AddStructuralProperty("State", EdmPrimitiveTypeKind.String);
            addressType.AddStructuralProperty("Country", EdmPrimitiveTypeKind.String);
            addressType.AddStructuralProperty("ZipCode", EdmPrimitiveTypeKind.String);
            model.AddElement(addressType);

            // Add navigations
            customerType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo()
            {
                Name = "Orders",
                Target = orderType,
                TargetMultiplicity = EdmMultiplicity.Many
            });
            orderType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo()
            {
                Name = "Customer",
                Target = customerType,
                TargetMultiplicity = EdmMultiplicity.One
            });

            var container = new EdmEntityContainer("Default", "Container");
            var customerSet = container.AddEntitySet("Customers", customerType);
            var orderSet = container.AddEntitySet("Orders", orderType);
            customerSet.AddNavigationTarget(customerType.NavigationProperties().Single(np => np.Name == "Orders"), orderSet);
            orderSet.AddNavigationTarget(orderType.NavigationProperties().Single(np => np.Name == "Customer"), customerSet);

            EntitySetLinkBuilderAnnotation linkAnnotation = new MockEntitySetLinkBuilderAnnotation();
            model.SetEntitySetLinkBuilder(customerSet, linkAnnotation);
            model.SetEntitySetLinkBuilder(orderSet, linkAnnotation);

            model.AddElement(container);
            return model;
        }
        static TableStorageQueryIndexInspector()
        {
            EdmModel = new EdmModel();
            TableServiceEntity = new EdmEntityType("Glimpse.WindowsAzure.Storage", "TableServiceEntity");
            TableServiceEntity.AddStructuralProperty("PartitionKey", EdmPrimitiveTypeKind.String);
            TableServiceEntity.AddStructuralProperty("RowKey", EdmPrimitiveTypeKind.String);
            TableServiceEntity.AddStructuralProperty("Timestamp", EdmPrimitiveTypeKind.DateTime);
            EdmModel.AddElement(TableServiceEntity);

            var container = new EdmEntityContainer("TestModel", "DefaultContainer");
            container.AddEntitySet("Entities", TableServiceEntity);
            EdmModel.AddElement(container);
        }
        public static IEdmModel SimpleCustomerOrderModel()
        {
            var model = new EdmModel();
            var customerType = new EdmEntityType("Default", "Customer");
            customerType.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32);
            customerType.AddStructuralProperty("FirstName", EdmPrimitiveTypeKind.String);
            customerType.AddStructuralProperty("LastName", EdmPrimitiveTypeKind.String);
            model.AddElement(customerType);

            var orderType = new EdmEntityType("Default", "Order");
            orderType.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32);
            orderType.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
            model.AddElement(orderType);

            var addressType = new EdmComplexType("Default", "Address");
            addressType.AddStructuralProperty("Street", EdmPrimitiveTypeKind.String);
            addressType.AddStructuralProperty("City", EdmPrimitiveTypeKind.String);
            addressType.AddStructuralProperty("State", EdmPrimitiveTypeKind.String);
            addressType.AddStructuralProperty("Country", EdmPrimitiveTypeKind.String);
            addressType.AddStructuralProperty("ZipCode", EdmPrimitiveTypeKind.String);
            model.AddElement(addressType);

            // Add navigations
            customerType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo() { Name = "Orders", Target = orderType, TargetMultiplicity = EdmMultiplicity.Many });
            orderType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo() { Name = "Customer", Target = customerType, TargetMultiplicity = EdmMultiplicity.One });

            var container = new EdmEntityContainer("Default", "Container");
            var customerSet = container.AddEntitySet("Customers", customerType);
            var orderSet = container.AddEntitySet("Orders", orderType);
            customerSet.AddNavigationTarget(customerType.NavigationProperties().Single(np => np.Name == "Orders"), orderSet);
            orderSet.AddNavigationTarget(orderType.NavigationProperties().Single(np => np.Name == "Customer"), customerSet);

            Mock<IEntitySetLinkBuilder> linkAnnotation = new Mock<IEntitySetLinkBuilder>();
            model.SetEntitySetLinkBuilderAnnotation(customerSet, linkAnnotation.Object);
            model.SetEntitySetLinkBuilderAnnotation(orderSet, linkAnnotation.Object);

            model.AddElement(container);
            return model;
        }
        public EdmDeltaModel(IEdmModel source, IEdmEntityType entityType, IEnumerable<string> propertyNames)
        {
            _source = source;
            _entityType = new EdmEntityType(entityType.Namespace, entityType.Name);

            foreach (var property in entityType.StructuralProperties())
            {
                if (propertyNames.Contains(property.Name))
                    _entityType.AddStructuralProperty(property.Name, property.Type, property.DefaultValueString, property.ConcurrencyMode);
            }

            foreach (var property in entityType.NavigationProperties())
            {
                if (propertyNames.Contains(property.Name))
                {
                    var navInfo = new EdmNavigationPropertyInfo()
                    {
                        ContainsTarget = property.ContainsTarget,
                        DependentProperties = property.DependentProperties,
                        Name = property.Name,
                        OnDelete = property.OnDelete,
                        Target = property.Partner != null
                            ? property.Partner.DeclaringEntityType()
                            : property.Type.TypeKind() == EdmTypeKind.Collection
                            ? (property.Type.Definition as IEdmCollectionType).ElementType.Definition as IEdmEntityType
                            : property.Type.TypeKind() == EdmTypeKind.Entity
                            ? property.Type.Definition as IEdmEntityType
                            : null,
                        TargetMultiplicity = property.Partner != null 
                            ? property.Partner.Multiplicity() 
                            : property.Type.TypeKind() == EdmTypeKind.Collection
                            ? EdmMultiplicity.Many
                            : property.Type.TypeKind() == EdmTypeKind.Entity
                            ? EdmMultiplicity.ZeroOrOne
                            : EdmMultiplicity.Unknown,
                    };
                    _entityType.AddUnidirectionalNavigation(navInfo);
                }
            }
        }
        public void GetEntityKeyValue_MultipleKeys_DerivedType()
        {
            // Arrange
            var entityInstance = new { Key1 = "key1", Key2 = 2, Key3 = true };
            EdmEntityType baseEntityType = new EdmEntityType("NS", "Name");
            baseEntityType.AddKeys(baseEntityType.AddStructuralProperty("Key1", EdmPrimitiveTypeKind.String));
            baseEntityType.AddKeys(baseEntityType.AddStructuralProperty("Key2", EdmPrimitiveTypeKind.Int32));
            baseEntityType.AddKeys(baseEntityType.AddStructuralProperty("Key3", EdmPrimitiveTypeKind.Boolean));
            EdmEntityType derivedEntityType = new EdmEntityType("NS", "Derived", baseEntityType);

            EntityInstanceContext entityInstanceContext = new EntityInstanceContext(_writeContext, derivedEntityType.AsReference(), entityInstance);

            // Act
            var keyValue = ConventionsHelpers.GetEntityKeyValue(entityInstanceContext);

            // Assert
            Assert.Equal("Key1='key1',Key2=2,Key3=true", keyValue);
        }
        public void GetEntityKeyValue_ThrowsForNullKeys_WithMultipleKeys()
        {
            // Arrange
            var entityInstance = new { Key1 = "abc", Key2 = "def", Key3 = (string)null };
            EdmEntityType entityType = new EdmEntityType("NS", "Name");
            entityType.AddKeys(entityType.AddStructuralProperty("Key1", EdmPrimitiveTypeKind.String));
            entityType.AddKeys(entityType.AddStructuralProperty("Key2", EdmPrimitiveTypeKind.Int32));
            entityType.AddKeys(entityType.AddStructuralProperty("Key3", EdmPrimitiveTypeKind.Boolean));

            EntityInstanceContext entityInstanceContext = new EntityInstanceContext(_writeContext, entityType.AsReference(), entityInstance);

            // Act & Assert
            Assert.Throws<InvalidOperationException>(
                () => ConventionsHelpers.GetEntityKeyValue(entityInstanceContext),
                "Key property 'Key3' of type 'NS.Name' is null. Key properties cannot have null values.");
        }
        public void GetEntityKeyValue_DerivedType()
        {
            // Arrange
            var entityInstance = new { Key = "key" };
            EdmEntityType baseEntityType = new EdmEntityType("NS", "Name");
            baseEntityType.AddKeys(baseEntityType.AddStructuralProperty("Key", EdmPrimitiveTypeKind.String));
            EdmEntityType derivedEntityType = new EdmEntityType("NS", "Derived", baseEntityType);

            EntityInstanceContext entityInstanceContext = new EntityInstanceContext(_writeContext, derivedEntityType.AsReference(), entityInstance);

            // Act
            var keyValue = ConventionsHelpers.GetEntityKeyValue(entityInstanceContext);

            // Assert
            Assert.Equal("'key'", keyValue);
        }
        public void Property_EntityInstance_EdmObjectHasCollectionProperty()
        {
            // Arrange
            EdmEntityType edmType = new EdmEntityType("NS", "Name");
            edmType.AddStructuralProperty(
                "CollectionProperty",
                new EdmCollectionTypeReference(
                    new EdmCollectionType(EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.Int32, isNullable: false)), isNullable: false));
            EdmModel model = new EdmModel();
            model.AddElement(edmType);
            model.SetAnnotationValue<ClrTypeAnnotation>(edmType, new ClrTypeAnnotation(typeof(TestEntity)));
            Mock<IEdmStructuredObject> edmObject = new Mock<IEdmStructuredObject>();
            object propertyValue = new List<int> { 42 };
            edmObject.Setup(e => e.TryGetValue("CollectionProperty", out propertyValue)).Returns(true);
            edmObject.Setup(e => e.GetEdmType()).Returns(new EdmEntityTypeReference(edmType, isNullable: false));

            EntityInstanceContext entityContext = new EntityInstanceContext { EdmModel = model, EdmObject = edmObject.Object, EntityType = edmType };

            // Act
            object resource = entityContext.EntityInstance;

            // Assert
            TestEntity testEntity = Assert.IsType<TestEntity>(resource);
            Assert.Equal(new[] { 42 }, testEntity.CollectionProperty);
        }
        public void GetEntityKeyValue_SingleKey_DifferentDataTypes(object value, object expectedValue)
        {
            // Arrange
            EdmEntityType entityType = new EdmEntityType("NS", "Name");
            entityType.AddKeys(entityType.AddStructuralProperty("Property", EdmPrimitiveTypeKind.String));
            var entityInstance = new { Property = value };

            EntityInstanceContext entityInstanceContext = new EntityInstanceContext(_writeContext, entityType.AsReference(), entityInstance);

            // Act
            var keyValue = ConventionsHelpers.GetEntityKeyValue(entityInstanceContext);

            // Assert
            Assert.Equal(expectedValue, keyValue);
        }
        private static IEdmModel CreateModel()
        {
            var model = new EdmModel();

            var orderType = new EdmEntityType("Default", "Order");
            orderType.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32);
            model.AddElement(orderType);

            var customerType = new EdmEntityType("Default", "Customer");
            customerType.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32);
            model.AddElement(customerType);

            // Add navigations
            orderType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo()
            {
                Name = "Customer",
                Target = customerType,
                TargetMultiplicity = EdmMultiplicity.One
            });

            var container = new EdmEntityContainer("Default", "Container");
            var orderSet = container.AddEntitySet("Orders", orderType);
            var customerSet = container.AddEntitySet("Customers", customerType);

            container.AddFunctionImport("GetId", new EdmPrimitiveTypeReference(
                EdmCoreModel.Instance.GetPrimitiveType(EdmPrimitiveTypeKind.Int32), true));

            orderSet.AddNavigationTarget(orderType.NavigationProperties().Single(np => np.Name == "Customer"),
                customerSet);

            model.AddElement(container);
            return model;
        }
 /// <summary>
 /// Create a new type with the standard set of properties(PK, RK and TimeStamp).
 /// </summary>
 /// <param name="namespaceName">Namespace the entity belongs to.</param>
 /// <param name="name">Name of the entity.</param>
 /// <returns>The EdmEntityType created.</returns>
 internal static EdmEntityType CreateEntityType(string namespaceName, string name)
 {
     EdmEntityType entityType = new EdmEntityType(namespaceName, name, null, false, true);
     entityType.AddKeys(
         entityType.AddStructuralProperty("RowKey", EdmPrimitiveTypeKind.String),
         entityType.AddStructuralProperty("PartitionKey", EdmPrimitiveTypeKind.String));
         entityType.AddStructuralProperty("Timestamp", EdmCoreModel.Instance.GetDateTime(false), null, EdmConcurrencyMode.Fixed);  // We need this because we want to ensure that this property is not used for optimistic concurrency checks. 
     return entityType;
 }
        public void Property_EntityInstance_CanBeBuiltFromIEdmObject()
        {
            // Arrange
            EdmEntityType edmType = new EdmEntityType("NS", "Name");
            edmType.AddStructuralProperty("Property", EdmPrimitiveTypeKind.Int32);
            EdmModel model = new EdmModel();
            model.AddElement(edmType);
            model.SetAnnotationValue<ClrTypeAnnotation>(edmType, new ClrTypeAnnotation(typeof(TestEntity)));
            Mock<IEdmEntityObject> edmObject = new Mock<IEdmEntityObject>();
            object propertyValue = 42;
            edmObject.Setup(e => e.TryGetPropertyValue("Property", out propertyValue)).Returns(true);
            edmObject.Setup(e => e.GetEdmType()).Returns(new EdmEntityTypeReference(edmType, isNullable: false));

            EntityInstanceContext entityContext = new EntityInstanceContext { EdmModel = model, EdmObject = edmObject.Object, EntityType = edmType };

            // Act
            object resource = entityContext.EntityInstance;

            // Assert
            TestEntity testEntity = Assert.IsType<TestEntity>(resource);
            Assert.Equal(42, testEntity.Property);
        }
        public void ToDictionary_ContainsAllProperties_FromContainer()
        {
            // Arrange
            EdmEntityType entityType = new EdmEntityType("NS", "Name");
            entityType.AddStructuralProperty("SampleProperty", EdmPrimitiveTypeKind.Int32);

            EdmModel model = new EdmModel();
            model.AddElement(entityType);
            model.SetAnnotationValue(entityType, new ClrTypeAnnotation(typeof(TestEntity)));

            MockPropertyContainer container = new MockPropertyContainer();
            container.Properties.Add("Property", 42);
            SelectExpandWrapper<TestEntity> wrapper = new SelectExpandWrapper<TestEntity>
            {
                Container = container,
                ModelID = ModelContainer.GetModelID(model)
            };

            // Act
            var result = wrapper.ToDictionary();

            // Assert
            Assert.Equal(42, result["Property"]);
        }
        public void ToDictionary_Throws_IfMapperProvider_ReturnsNullPropertyMapper()
        {
            // Arrange
            EdmEntityType entityType = new EdmEntityType("NS", "Name");
            entityType.AddStructuralProperty("SampleProperty", EdmPrimitiveTypeKind.Int32);

            EdmModel model = new EdmModel();
            model.AddElement(entityType);
            model.SetAnnotationValue(entityType, new ClrTypeAnnotation(typeof(TestEntity)));
            IEdmTypeReference edmType = new EdmEntityTypeReference(entityType, isNullable: false);

            SelectExpandWrapper<TestEntity> wrapper = new SelectExpandWrapper<TestEntity>
            {
                Instance = new TestEntity { SampleProperty = 42 },
                ModelID = ModelContainer.GetModelID(model)
            };

            Func<IEdmModel, IEdmStructuredType, IPropertyMapper> mapperProvider =
                (IEdmModel m, IEdmStructuredType t) => null;

            // Act & Assert
            Assert.Throws<InvalidOperationException>(() =>
                wrapper.ToDictionary(mapperProvider: mapperProvider),
                "The mapper provider must return a valid 'System.Web.Http.OData.Query.IPropertyMapper' instance for the given 'NS.Name' IEdmType.");
        }
        public void ToDictionary_AppliesMappingToAllProperties_IfInstanceIsNotNull()
        {
            // Arrange
            EdmEntityType entityType = new EdmEntityType("NS", "Name");
            entityType.AddStructuralProperty("SampleProperty", EdmPrimitiveTypeKind.Int32);

            EdmModel model = new EdmModel();
            model.AddElement(entityType);
            model.SetAnnotationValue(entityType, new ClrTypeAnnotation(typeof(TestEntity)));
            IEdmTypeReference edmType = new EdmEntityTypeReference(entityType, isNullable: false);

            SelectExpandWrapper<TestEntity> testWrapper = new SelectExpandWrapper<TestEntity>
            {
                Instance = new TestEntity { SampleProperty = 42 },
                ModelID = ModelContainer.GetModelID(model)
            };

            Mock<IPropertyMapper> mapperMock = new Mock<IPropertyMapper>();
            mapperMock.Setup(m => m.MapProperty("SampleProperty")).Returns("Sample");
            Func<IEdmModel, IEdmStructuredType, IPropertyMapper> mapperProvider =
                (IEdmModel m, IEdmStructuredType t) => mapperMock.Object;

            // Act
            var result = testWrapper.ToDictionary(mapperProvider);

            // Assert
            Assert.Equal(42, result["Sample"]);
        }
        public void ToDictionary_Throws_IfMappingIsNullOrEmpty_ForAGivenProperty(string propertyMapping)
        {
            // Arrange
            EdmEntityType entityType = new EdmEntityType("NS", "Name");
            entityType.AddStructuralProperty("SampleProperty", EdmPrimitiveTypeKind.Int32);

            EdmModel model = new EdmModel();
            model.AddElement(entityType);
            model.SetAnnotationValue(entityType, new ClrTypeAnnotation(typeof(TestEntity)));
            IEdmTypeReference edmType = new EdmEntityTypeReference(entityType, isNullable: false);

            SelectExpandWrapper<TestEntity> testWrapper = new SelectExpandWrapper<TestEntity>
            {
                Instance = new TestEntity { SampleProperty = 42 },
                ModelID = ModelContainer.GetModelID(model)
            };

            Mock<IPropertyMapper> mapperMock = new Mock<IPropertyMapper>();
            mapperMock.Setup(m => m.MapProperty("SampleProperty")).Returns(propertyMapping);
            Func<IEdmModel, IEdmStructuredType, IPropertyMapper> mapperProvider =
                (IEdmModel m, IEdmStructuredType t) => mapperMock.Object;

            // Act & Assert
            Assert.Throws<InvalidOperationException>(() =>
                testWrapper.ToDictionary(mapperProvider),
                "The key mapping for the property 'SampleProperty' can't be null or empty.");
        }
        EdmEntityTypeWrapper AddTable(EdmModel model, TableData dataBuilder)
        {
            var propertyMap = new Dictionary<Field, EdmStructuralProperty>();

            var table = new EdmEntityType("sitecore.com", dataBuilder.Name);
            foreach (var field in dataBuilder.Schema.Fields)
            {
                var prop = table.AddStructuralProperty(field.Name, GetEdmType(field.ValueType), IsNullable(field.ValueType));                
                if (field.FieldType == FieldType.Key)
                {
                    table.AddKeys(prop);
                }
                propertyMap.Add(field, prop);
            }            
            model.AddElement(table);            

            return new EdmEntityTypeWrapper {Type = table, Properties = propertyMap};
        }
        public CustomersModelWithInheritance()
        {
            EdmModel model = new EdmModel();

            // complex type address
            EdmComplexType address = new EdmComplexType("NS", "Address");
            address.AddStructuralProperty("Street", EdmPrimitiveTypeKind.String);
            address.AddStructuralProperty("City", EdmPrimitiveTypeKind.String);
            address.AddStructuralProperty("State", EdmPrimitiveTypeKind.String);
            address.AddStructuralProperty("ZipCode", EdmPrimitiveTypeKind.String);
            address.AddStructuralProperty("Country", EdmPrimitiveTypeKind.String);
            model.AddElement(address);

            // entity type customer
            EdmEntityType customer = new EdmEntityType("NS", "Customer");
            customer.AddKeys(customer.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32));
            customer.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
            customer.AddStructuralProperty("Address", new EdmComplexTypeReference(address, isNullable: true));
            model.AddElement(customer);

            // derived entity type special customer
            EdmEntityType specialCustomer = new EdmEntityType("NS", "SpecialCustomer", customer);
            specialCustomer.AddStructuralProperty("SpecialCustomerProperty", EdmPrimitiveTypeKind.Guid);
            model.AddElement(specialCustomer);

            // entity type order
            EdmEntityType order = new EdmEntityType("NS", "Order");
            order.AddKeys(order.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32));
            order.AddStructuralProperty("Amount", EdmPrimitiveTypeKind.Int32);
            model.AddElement(order);

            // derived entity type special order
            EdmEntityType specialOrder = new EdmEntityType("NS", "SpecialOrder", order);
            specialOrder.AddStructuralProperty("SpecialOrderProperty", EdmPrimitiveTypeKind.Guid);
            model.AddElement(specialOrder);

            // entity sets
            EdmEntityContainer container = new EdmEntityContainer("NS", "ModelWithInheritance");
            model.AddElement(container);
            EdmEntitySet customers = container.AddEntitySet("Customers", customer);
            EdmEntitySet orders = container.AddEntitySet("Orders", order);

            // actions
            EdmFunctionImport upgradeCustomer = container.AddFunctionImport(
                "upgrade", returnType: null, entitySet: new EdmEntitySetReferenceExpression(customers), sideEffecting: true, composable: false, bindable: true);
            upgradeCustomer.AddParameter("entity", new EdmEntityTypeReference(customer, false));
            EdmFunctionImport upgradeSpecialCustomer = container.AddFunctionImport(
                "specialUpgrade", returnType: null, entitySet: new EdmEntitySetReferenceExpression(customers), sideEffecting: true, composable: false, bindable: true);
            upgradeSpecialCustomer.AddParameter("entity", new EdmEntityTypeReference(specialCustomer, false));

            // navigation properties
            customers.AddNavigationTarget(
                customer.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo
                {
                    Name = "Orders",
                    TargetMultiplicity = EdmMultiplicity.Many,
                    Target = order
                }),
                orders);
            orders.AddNavigationTarget(
                 order.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo
                 {
                     Name = "Customer",
                     TargetMultiplicity = EdmMultiplicity.ZeroOrOne,
                     Target = customer
                 }),
                customers);

            // navigation properties on derived types.
            customers.AddNavigationTarget(
                specialCustomer.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo
                {
                    Name = "SpecialOrders",
                    TargetMultiplicity = EdmMultiplicity.Many,
                    Target = order
                }),
                orders);
            orders.AddNavigationTarget(
                 specialOrder.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo
                 {
                     Name = "SpecialCustomer",
                     TargetMultiplicity = EdmMultiplicity.ZeroOrOne,
                     Target = customer
                 }),
                customers);
            model.SetAnnotationValue<BindableProcedureFinder>(model, new BindableProcedureFinder(model));

            // set properties
            Model = model;
            Container = container;
            Customer = customer;
            Order = order;
            Address = address;
            SpecialCustomer = specialCustomer;
            SpecialOrder = specialOrder;
            Orders = orders;
            Customers = customers;
            UpgradeCustomer = upgradeCustomer;
        }
        public void ToDictionary_ContainsAllStructuralProperties_IfInstanceIsNotNull()
        {
            // Arrange
            EdmModel model = new EdmModel();
            EdmEntityType entityType = new EdmEntityType("NS", "Name");
            model.AddElement(entityType);
            model.SetAnnotationValue(entityType, new ClrTypeAnnotation(typeof(TestEntity)));
            entityType.AddStructuralProperty("SampleProperty", EdmPrimitiveTypeKind.Int32);
            IEdmTypeReference edmType = new EdmEntityTypeReference(entityType, isNullable: false);
            SelectExpandWrapper<TestEntity> testWrapper = new SelectExpandWrapper<TestEntity>
            {
                Instance = new TestEntity { SampleProperty = 42 },
                ModelID = ModelContainer.GetModelID(model)
            };

            // Act
            var result = testWrapper.ToDictionary();

            // Assert
            Assert.Equal(42, result["SampleProperty"]);
        }
        public void DollarMetadata_Works_WithMultipleReferentialConstraints_ForUntypedModel()
        {
            // Arrange
            EdmModel model = new EdmModel();

            EdmEntityType customer = new EdmEntityType("DefaultNamespace", "Customer");
            customer.AddKeys(customer.AddStructuralProperty("CustomerId", EdmCoreModel.Instance.GetInt32(false)));
            customer.AddStructuralProperty("Name", EdmCoreModel.Instance.GetString(false));
            model.AddElement(customer);

            EdmEntityType order = new EdmEntityType("DefaultNamespace", "Order");
            order.AddKeys(order.AddStructuralProperty("OrderId", EdmCoreModel.Instance.GetInt32(false)));
            EdmStructuralProperty orderCustomerId = order.AddStructuralProperty("CustomerForeignKey", EdmCoreModel.Instance.GetInt32(true));
            model.AddElement(order);

            customer.AddBidirectionalNavigation(
                new EdmNavigationPropertyInfo
                {
                    Name = "Orders",
                    Target = order,
                    TargetMultiplicity = EdmMultiplicity.Many
                },
                new EdmNavigationPropertyInfo
                {
                    Name = "Customer",
                    TargetMultiplicity = EdmMultiplicity.ZeroOrOne,
                    DependentProperties = new[] { orderCustomerId },
                });

            const string expect =
                "        <ReferentialConstraint>\r\n" +
                "          <Principal Role=\"Customer\">\r\n" +
                "            <PropertyRef Name=\"CustomerId\" />\r\n" +
                "          </Principal>\r\n" +
                "          <Dependent Role=\"Orders\">\r\n" +
                "            <PropertyRef Name=\"CustomerForeignKey\" />\r\n" +
                "          </Dependent>\r\n" +
                "        </ReferentialConstraint>";

            HttpServer server = new HttpServer();
            server.Configuration.Routes.MapODataServiceRoute("odata", "odata", model);

            HttpClient client = new HttpClient(server);

            // Act
            HttpResponseMessage response = client.GetAsync("http://localhost/odata/$metadata").Result;

            // Assert
            Assert.True(response.IsSuccessStatusCode);
            Assert.Equal("application/xml", response.Content.Headers.ContentType.MediaType);
            Assert.Contains(expect, response.Content.ReadAsStringAsync().Result);
        }