public void ODataConventionModelBuilder_CreateArrayEnumTypeCollectionPropertyWithInEntityType() { // Arrange var builder = new ODataConventionModelBuilder(); builder.EntityType <ArrayEnumTypePropertyTestModel>(); IEdmModel model = builder.GetEdmModel(); IEdmEntityType entityType = model.SchemaElements.OfType <IEdmEntityType>().Single(); // Act & Assert Assert.Equal(3, entityType.Properties().Count()); var colors = entityType.Properties().SingleOrDefault(p => p.Name == "Colors"); Assert.NotNull(colors); Assert.True(colors.Type.IsCollection()); Assert.False(colors.Type.IsNullable); Assert.True(((IEdmCollectionTypeReference)colors.Type).ElementType().IsEnum()); var nullableColors = entityType.Properties().SingleOrDefault(p => p.Name == "NullableColors"); Assert.NotNull(nullableColors); Assert.True(nullableColors.Type.IsCollection()); Assert.True(nullableColors.Type.IsNullable); Assert.True(((IEdmCollectionTypeReference)nullableColors.Type).ElementType().IsEnum()); }
public async Task ModelBuilderTest() { // Arrange string requestUri = string.Format("{0}/odata/$metadata", this.BaseAddress); HttpResponseMessage response = await this.Client.GetAsync(requestUri); var stream = await response.Content.ReadAsStreamAsync(); // Act IODataResponseMessage message = new ODataMessageWrapper(stream, response.Content.Headers); var reader = new ODataMessageReader(message); IEdmModel edmModel = reader.ReadMetadataDocument(); // Assert IEdmEntityType weatherForecast = edmModel.SchemaElements.OfType <IEdmEntityType>().First(); Assert.Equal("WeatherForecast", weatherForecast.Name); Assert.Equal(3, weatherForecast.Properties().Count()); // Enum Property 1 var status = weatherForecast.Properties().SingleOrDefault(p => p.Name == "Status"); Assert.True(status.Type.IsEnum()); // Enum Property 2 var skill = weatherForecast.Properties().SingleOrDefault(p => p.Name == "Skill"); Assert.True(skill.Type.IsEnum()); }
public EntityTypeConfiguration <TEntity> Filter(QueryOptionSetting setting) { foreach (IEdmProperty edmProperty in _entityType.Properties()) { _modelBuilder.ModelBoundSettingsBuilder.SetFilter(edmProperty, setting == QueryOptionSetting.Allowed); } return(this); }
public void ParserTestDuplicateEntityTypes() { var csdls = ODataTestModelBuilder.InvalidCsdl.DuplicateEntityTypes; var model = this.GetParserResult(csdls); IEdmEntityContainer entityContainer = model.EntityContainer; Assert.AreEqual("DefaultContainer", entityContainer.Name, "Invalid entity container name"); Assert.IsTrue(entityContainer.Elements.Count() == 2, "Entity container has invalid amount of elements"); Assert.AreEqual(EdmContainerElementKind.EntitySet, entityContainer.Elements.ElementAt(0).ContainerElementKind, "Invalid container element kind"); Assert.AreEqual(EdmContainerElementKind.EntitySet, entityContainer.Elements.ElementAt(1).ContainerElementKind, "Invalid container element kind"); IEdmEntitySet entitySetElement1 = (IEdmEntitySet)entityContainer.Elements.ElementAt(0); Assert.AreEqual("DuplicateEntityType", entitySetElement1.Name, "Invalid entity set name"); Assert.AreEqual("TestModel.DuplicateEntityType", entitySetElement1.EntityType().FullName(), "Invalid entity set element type"); IEdmEntitySet entitySetElement2 = (IEdmEntitySet)entityContainer.Elements.ElementAt(1); Assert.AreEqual("DuplicateEntityType", entitySetElement2.Name, "Invalid entity set name"); Assert.AreEqual("TestModel.DuplicateEntityType", entitySetElement2.EntityType().FullName(), "Invalid entity set element type"); Assert.IsTrue(model.SchemaElements.Count() == 3, "Invalid schema element count"); Assert.AreEqual(EdmSchemaElementKind.TypeDefinition, model.SchemaElements.ElementAt(0).SchemaElementKind, "Invalid schema element kind"); Assert.AreEqual(EdmSchemaElementKind.TypeDefinition, model.SchemaElements.ElementAt(1).SchemaElementKind, "Invalid schema element kind"); IEdmEntityType entityTypeElement1 = (IEdmEntityType)model.SchemaElements.ElementAt(0); Assert.AreEqual("TestModel.DuplicateEntityType", entityTypeElement1.FullName(), "Invalid entity type full name"); Assert.AreEqual("DuplicateEntityType", entityTypeElement1.Name, "Invalid entity type name"); Assert.IsTrue(entityTypeElement1.Properties().Count() == 1, "Invalid property count"); Assert.AreEqual("Id", entityTypeElement1.Properties().Single().Name, "Invalid property name"); Assert.IsTrue(entityTypeElement1.DeclaredKey.Count() == 1, "Invalid declare key count for entity type"); IEdmEntityType entityTypeElement2 = (IEdmEntityType)model.SchemaElements.ElementAt(1); Assert.AreEqual("TestModel.DuplicateEntityType", entityTypeElement2.FullName(), "Invalid entity type full name"); Assert.AreEqual("DuplicateEntityType", entityTypeElement2.Name, "Invalid entity type name"); Assert.IsTrue(entityTypeElement2.Properties().Count() == 1, "Invalid property count"); Assert.AreEqual("Id", entityTypeElement2.Properties().Single().Name, "Invalid property name"); Assert.IsTrue(entityTypeElement2.DeclaredKey.Count() == 1, "Invalid declare key count for entity type"); var expectedErrors = new EdmLibTestErrors() { { 5, 10, EdmErrorCode.DuplicateEntityContainerMemberName }, { 13, 6, EdmErrorCode.AlreadyDefined }, { 4, 10, EdmErrorCode.BadUnresolvedEntityType }, { 5, 10, EdmErrorCode.BadUnresolvedEntityType } }; IEnumerable <EdmError> actualErrors = null; model.Validate(out actualErrors); this.CompareErrors(actualErrors, expectedErrors); }
public void ODataConventionModelBuilder_CreateNullableEnumTypePropertyInEntityType() { // Arrange IEdmEntityType entityType = AddEntityTypeWithODataConventionModelBuilder(); // Act & Assert Assert.Equal(5, entityType.Properties().Count()); var nullableColor = entityType.Properties().SingleOrDefault(p => p.Name == "NullableColor"); Assert.NotNull(nullableColor); Assert.True(nullableColor.Type.IsEnum()); Assert.True(nullableColor.Type.IsNullable); }
public void ODataConventionModelBuilder_CreateEnumTypeCollectionPropertyInEntityType() { // Arrange IEdmEntityType entityType = AddEntityTypeWithODataConventionModelBuilder(); // Act & Assert Assert.Equal(5, entityType.Properties().Count()); var colors = entityType.Properties().SingleOrDefault(p => p.Name == "Colors"); Assert.NotNull(colors); Assert.True(colors.Type.IsCollection()); Assert.True(((IEdmCollectionTypeReference)colors.Type).ElementType().IsEnum()); }
public void ODataConventionModelBuilder_CreateLongEnumTypePropertyInEntityType() { // Arrange IEdmEntityType entityType = AddEntityTypeWithODataConventionModelBuilder(); // Act & Assert Assert.Equal(5, entityType.Properties().Count()); var longEnum = entityType.Properties().SingleOrDefault(p => p.Name == "LongEnum"); Assert.NotNull(longEnum); Assert.True(longEnum.Type.IsEnum()); Assert.False(longEnum.Type.IsNullable); Assert.Same(EdmCoreModel.Instance.GetInt64(false).Definition, longEnum.Type.AsEnum().EnumDefinition().UnderlyingType); }
private void BuildAttributes(IEdmEntityType edmEntityType, Type clrEntityType) { IEnumerable <T> attributes = clrEntityType.GetCustomAttributes <T>(); foreach (T attribute in attributes) { if (GetConfigurations(attribute).Count == 0) { foreach (IEdmProperty edmProperty in edmEntityType.Properties()) { SetProperty(edmProperty, IsAllowed(attribute)); } } else { foreach (KeyValuePair <String, SelectExpandType> configuration in GetConfigurations(attribute)) { IEdmProperty edmProperty = edmEntityType.GetPropertyIgnoreCase(configuration.Key); SetProperty(edmProperty, configuration.Value); } } } foreach (IEdmProperty edmProperty in edmEntityType.Properties()) { PropertyInfo clrProperty = clrEntityType.GetPropertyIgnoreCase(edmProperty); if (edmProperty is IEdmNavigationProperty navigationProperty) { attributes = clrProperty.GetCustomAttributes <T>(); IEdmEntityType navigationEntityType = navigationProperty.ToEntityType(); foreach (T attribute in attributes) { SetProperty(navigationProperty, IsAllowed(attribute)); foreach (KeyValuePair <String, SelectExpandType> configuration in GetConfigurations(attribute)) { IEdmProperty edmProperty2 = navigationEntityType.GetPropertyIgnoreCase(configuration.Key); SetProperty(edmProperty2, configuration.Value, navigationProperty); } } } else { var attribute = (T)clrProperty.GetCustomAttribute(typeof(T)); if (attribute != null) { SetProperty(edmProperty, IsAllowed(attribute)); } } } }
public void GetEdmModel_Works_WithSingleForeignKeyProperty() { // Arrange ODataModelBuilder builder = new ODataModelBuilder(); EntityTypeConfiguration <User> userType = builder.Entity <User>(); userType.HasKey(u => u.UserId).HasMany(u => u.Roles); EntityTypeConfiguration <Role> roleType = builder.Entity <Role>(); roleType.HasKey(r => r.RoleId) .HasRequired(r => r.User, (r, u) => r.UserForeignKey == u.UserId) .CascadeOnDelete(); // Act IEdmModel model = builder.GetEdmModel(); // Assert Assert.NotNull(model); IEdmEntityType roleEntityType = model.AssertHasEntityType(typeof(Role)); IEdmNavigationProperty usersNav = roleEntityType.AssertHasNavigationProperty(model, "User", typeof(User), false, EdmMultiplicity.One); Assert.Equal(EdmOnDeleteAction.Cascade, usersNav.OnDelete); IEdmStructuralProperty dependentProperty = Assert.Single(usersNav.DependentProperties); Assert.Equal("UserForeignKey", dependentProperty.Name); IEdmProperty edmProperty = Assert.Single(roleEntityType.Properties().Where(c => c.Name == "UserForeignKey")); Assert.False(edmProperty.Type.IsNullable); }
public static void ConvertOdataPropertyToGridColumns(IEdmEntityType pType, ref List <MGridColumn> pColumns, int pMaxDepth, string pPath = "", int pDepth = 0) { if (pDepth > pMaxDepth) { return; } foreach (var property in pType.Properties()) { if (property is IEdmNavigationProperty navProp) { var pi = navProp.GetType().GetProperty("TargetEntityType", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); var targetType = pi.GetValue(navProp) as IEdmEntityType; if (targetType != null) { ConvertOdataPropertyToGridColumns(targetType, ref pColumns, pMaxDepth, pPath + navProp.Name + ".", pDepth + 1); } continue; } pColumns.Add(new MGridColumn() { Property = pPath + property.Name, PropertyType = GetType(property.Type) }); } }
public void GetEdmModel_WorksOnModelBuilder_ForDerivedEntityType() { // Arrange ODataModelBuilder builder = new ODataModelBuilder(); builder.EntityType <EntityTypeWithAnnotation>() .HasKey(p => p.Id) .HasInstanceAnnotations(p => p.InstanceAnnotations); builder.EntityType <DerivedEntityTypeWithAnnotation>().DerivesFrom <EntityTypeWithAnnotation>(); // Act IEdmModel model = builder.GetEdmModel(); // Assert Assert.NotNull(model); IEdmEntityType baseEntityType = Assert.Single(model.SchemaElements.OfType <IEdmEntityType>().Where(c => c.Name == "EntityTypeWithAnnotation")); Assert.Single(baseEntityType.Properties()); IEdmEntityType derivedEntityType = Assert.Single(model.SchemaElements.OfType <IEdmEntityType>().Where(c => c.Name == "DerivedEntityTypeWithAnnotation")); InstanceAnnotationContainerAnnotation basePropertyAnnotation = model.GetAnnotationValue <InstanceAnnotationContainerAnnotation>(baseEntityType); Assert.Equal("InstanceAnnotations", basePropertyAnnotation.PropertyInfo.Name); InstanceAnnotationContainerAnnotation derivedPropertyAnnotation = model.GetAnnotationValue <InstanceAnnotationContainerAnnotation>(derivedEntityType); Assert.Null(derivedPropertyAnnotation); }
public void GetEdmModel_WorksOnModelBuilder_ForEntityType_InstanceAnnotation(bool setInstanceAnnotationContainer) { // Arrange ODataModelBuilder builder = new ODataModelBuilder(); var entity = builder.EntityType <EntityTypeWithAnnotation>().HasKey(p => p.Id); if (setInstanceAnnotationContainer) { entity.HasInstanceAnnotations(p => p.InstanceAnnotations); } // Act IEdmModel model = builder.GetEdmModel(); // Assert Assert.NotNull(model); IEdmEntityType entityType = Assert.Single(model.SchemaElements.OfType <IEdmEntityType>().Where(c => c.Name == "EntityTypeWithAnnotation")); Assert.Single(entityType.Properties()); InstanceAnnotationContainerAnnotation instanceAnnoteDict = model.GetAnnotationValue <InstanceAnnotationContainerAnnotation>(entityType); if (setInstanceAnnotationContainer) { Assert.Equal("InstanceAnnotations", instanceAnnoteDict.PropertyInfo.Name); } else { Assert.Null(instanceAnnoteDict); } }
public void CanCreateEntityWithEnumKey() { // Arrange ODataModelBuilder builder = new ODataModelBuilder(); var enumEntityType = builder.EntityType <EnumModel>(); enumEntityType.HasKey(c => c.Simple); enumEntityType.Property(c => c.Id); // Act IEdmModel model = builder.GetServiceModel(); // Assert IEdmEntityType entityType = model.SchemaElements.OfType <IEdmEntityType>() .FirstOrDefault(c => c.Name == "EnumModel"); Assert.NotNull(entityType); Assert.Equal(2, entityType.Properties().Count()); Assert.Single(entityType.DeclaredKey); IEdmStructuralProperty key = entityType.DeclaredKey.First(); Assert.Equal(EdmTypeKind.Enum, key.Type.TypeKind()); Assert.Equal("Microsoft.OData.ModelBuilder.Tests.TestModels.SimpleEnum", key.Type.Definition.FullTypeName()); }
internal static bool ContainsProperty(this IEdmType type, IEdmProperty property) { Func <IEdmProperty, bool> predicate = null; Func <IEdmProperty, bool> func2 = null; Func <IEdmNavigationProperty, bool> func3 = null; IEdmComplexType type2 = type as IEdmComplexType; if (type2 != null) { if (predicate == null) { predicate = p => p == property; } return(type2.Properties().Any <IEdmProperty>(predicate)); } IEdmEntityType type3 = type as IEdmEntityType; if (type3 == null) { return(false); } if (func2 == null) { func2 = p => p == property; } if (type3.Properties().Any <IEdmProperty>(func2)) { return(true); } if (func3 == null) { func3 = p => p == property; } return(type3.NavigationProperties().Any <IEdmNavigationProperty>(func3)); }
///// <summary> ///// Filters the list of properties and returns only MultiValue of primitive types and complex types. ///// </summary> ///// <param name="properties">The properties.</param> ///// <returns>Filtered list of properties.</returns> //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Multi", // Justification = "Matches product API, but is explicitly 'unrecognized' by code-analysis")] //public static IEnumerable<QueryProperty> MultiValue(this IEnumerable<QueryProperty> properties) //{ // ExceptionUtilities.CheckArgumentNotNull(properties, "properties"); // return properties.Where(property => property.IsMultiValue()); //} ///// <summary> ///// Filters the list of properties and returns only MultiValue of primitive types and complex types. ///// </summary> ///// <param name="properties">The properties.</param> ///// <param name="specificType">Type of multivalue to select, Primitive or Complex</param> ///// <returns>Filtered list of properties.</returns> //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Multi", // Justification = "Matches product API, but is explicitly 'unrecognized' by code-analysis")] //public static IEnumerable<QueryProperty> MultiValue(this IEnumerable<QueryProperty> properties, MultiValueType specificType) //{ // ExceptionUtilities.CheckArgumentNotNull(properties, "properties"); // return properties.Where(property => property.IsMultiValue(specificType)); //} ///// <summary> ///// Filters the list of properties and returns only MultiValue of primitive types and complex types. ///// </summary> ///// <param name="properties">The properties.</param> ///// <returns>Filtered list of properties.</returns> //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Multi", // Justification = "Matches product API, but is explicitly 'unrecognized' by code-analysis")] //public static IEnumerable<MemberProperty> MultiValue(this IEnumerable<MemberProperty> properties) //{ // ExceptionUtilities.CheckArgumentNotNull(properties, "properties"); // return properties.Where(property => property.IsMultiValue()); //} ///// <summary> ///// Filters the list of properties and returns only ComplexProperties. ///// </summary> ///// <param name="properties">The properties.</param> ///// <returns>Filtered list of properties.</returns> //public static IEnumerable<MemberProperty> ComplexProperties(this IEnumerable<MemberProperty> properties) //{ // ExceptionUtilities.CheckArgumentNotNull(properties, "properties"); // return properties.Where(property => property.PropertyType is ComplexDataType); //} ///// <summary> ///// Filters the list of properties and returns only MultiValue of primitive types and complex types. ///// </summary> ///// <param name="properties">The properties.</param> ///// <param name="specificType">Type of multivalue to select, Primitive or Complex</param> ///// <returns>Filtered list of properties.</returns> //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Multi", // Justification = "Matches product API, but is explicitly 'unrecognized' by code-analysis")] //public static IEnumerable<MemberProperty> MultiValue(this IEnumerable<MemberProperty> properties, MultiValueType specificType) //{ // ExceptionUtilities.CheckArgumentNotNull(properties, "properties"); // return properties.Where(property => property.IsMultiValue(specificType)); //} ///// <summary> ///// Builds a MultiValue Type based on the DataType passed in ///// </summary> ///// <param name="elementType">Element Type to be used to create a MultiValue type</param> ///// <returns>MultiValue Type Name</returns> //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Multi", // Justification = "Matches product API, but is explicitly 'unrecognized' by code-analysis")] //public static string BuildMultiValueTypeName(this DataType elementType) //{ // ExceptionUtilities.CheckArgumentNotNull(elementType, "elementType"); // PrimitiveDataType primitiveDataType = elementType as PrimitiveDataType; // ComplexDataType complexDataType = elementType as ComplexDataType; // if (primitiveDataType != null) // { // string edmTypeName = primitiveDataType.GetFacetValue<EdmTypeNameFacet, string>(null); // string edmNamespace = primitiveDataType.GetFacetValue<EdmNamespaceFacet, string>(null); // if (!string.IsNullOrEmpty(edmTypeName) && !string.IsNullOrEmpty(edmNamespace)) // { // edmTypeName = edmNamespace + '.' + edmTypeName; // } // if (!string.IsNullOrEmpty(edmTypeName)) // { // edmTypeName = "Collection(" + edmTypeName + ")"; // } // return edmTypeName; // } // else // { // ExceptionUtilities.Assert(complexDataType != null, "Unexpected TypeName to create for a Collection '{0}'", elementType); // return "Collection(" + complexDataType.Definition.FullName + ")"; // } //} ///// <summary> ///// Returns true if the Query Property is a collection/MultiValue type. ///// </summary> ///// <param name="property">The property</param> ///// <returns>true, if it is Edm.MultiValue; false otherwise.</returns> //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Multi", // Justification = "Matches product API, but is explicitly 'unrecognized' by code-analysis")] //public static bool IsMultiValue(this QueryProperty property) //{ // ExceptionUtilities.CheckArgumentNotNull(property, "property"); // var bagType = property.PropertyType as QueryCollectionType; // return (bagType != null) && (bagType.ElementType is QueryScalarType || bagType.ElementType is QueryComplexType); //} ///// <summary> ///// Returns true if the Query Property is a collection/MultiValue type. ///// </summary> ///// <param name="property">The property</param> ///// <param name="specificType">Primitive or Complex param to look at type and determine if its either</param> ///// <returns>true, if it is Edm.MultiValue; false otherwise.</returns> //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Multi", // Justification = "Matches product API, but is explicitly 'unrecognized' by code-analysis")] //public static bool IsMultiValue(this QueryProperty property, MultiValueType specificType) //{ // ExceptionUtilities.CheckArgumentNotNull(property, "property"); // var propertyBagType = property.PropertyType as QueryCollectionType; // if (propertyBagType != null && specificType == MultiValueType.Primitive && propertyBagType.ElementType is QueryScalarType) // { // return true; // } // else if (propertyBagType != null && specificType == MultiValueType.Complex && propertyBagType.ElementType is QueryComplexType) // { // return true; // } // return false; //} ///// <summary> ///// Returns true if the Query Property is a collection/MultiValue type. ///// </summary> ///// <param name="property">The property</param> ///// <returns>true, if it is Edm.MultiValue; false otherwise.</returns> //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Multi", // Justification = "Matches product API, but is explicitly 'unrecognized' by code-analysis")] //public static bool IsMultiValue(this MemberProperty property) //{ // ExceptionUtilities.CheckArgumentNotNull(property, "property"); // var bagType = property.PropertyType as CollectionDataType; // return (bagType != null) && (bagType.ElementDataType is PrimitiveDataType || bagType.ElementDataType is ComplexDataType); //} ///// <summary> ///// Returns true if the Query Property is a collection/MultiValue type. ///// </summary> ///// <param name="dataType">The data type</param> ///// <returns>true, if it is or contains an Edm.MultiValue; false otherwise.</returns> //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Multi", // Justification = "Matches product API, but is explicitly 'unrecognized' by code-analysis")] //public static bool HasCollection(this DataType dataType) //{ // ExceptionUtilities.CheckArgumentNotNull(dataType, "dataType"); // return VersionHelper.GatherDataTypes(dataType).Any(dt => dt is CollectionDataType); //} ///// <summary> ///// Returns true if the DataType is a spatial primitive type or a collection of primitive or a complex/entity type with a spatial property ///// </summary> ///// <param name="dataType">The data type</param> ///// <returns>true, if it is a spatial property or contains spatial properties; false otherwise.</returns> //public static bool IsSpatial(this DataType dataType) //{ // return VersionHelper.GatherDataTypes(dataType).Any(dt => dt is SpatialDataType); //} ///// <summary> ///// Returns true if the Query Property is a collection/MultiValue type. ///// </summary> ///// <param name="property">The property</param> ///// <param name="specificType">Primitive or Complex param to look at type and determine if its either</param> ///// <returns>true, if it is Edm.MultiValue; false otherwise.</returns> //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Multi", // Justification = "Matches product API, but is explicitly 'unrecognized' by code-analysis")] //public static bool IsMultiValue(this MemberProperty property, MultiValueType specificType) //{ // ExceptionUtilities.CheckArgumentNotNull(property, "property"); // var propertyBagType = property.PropertyType as CollectionDataType; // if (propertyBagType != null && specificType == MultiValueType.Primitive && propertyBagType.ElementDataType is PrimitiveDataType) // { // return true; // } // else if (propertyBagType != null && specificType == MultiValueType.Complex && propertyBagType.ElementDataType is ComplexDataType) // { // return true; // } // return false; //} ///// <summary> ///// Returns true if the Member Property is a stream type. ///// </summary> ///// <param name="property">The property</param> ///// <returns>true, if it is stream; false otherwise.</returns> //public static bool IsStream(this MemberProperty property) //{ // return property.PropertyType is StreamDataType; //} ///// <summary> ///// Returns true if the Query Property is a stream type. ///// </summary> ///// <param name="property">The property</param> ///// <returns>true, if it is stream; false otherwise.</returns> //public static bool IsStream(this QueryProperty property) //{ // var streamType = property.PropertyType as AstoriaQueryStreamType; // return streamType != null; //} ///// <summary> ///// Filters the list of properties and returns only streams. ///// </summary> ///// <param name="properties">The properties.</param> ///// <returns>Filtered list of properties.</returns> //public static IEnumerable<QueryProperty> Streams(this IEnumerable<QueryProperty> properties) //{ // return properties.Where(property => property.IsStream() && property.Name != AstoriaQueryStreamType.DefaultStreamPropertyName); //} /// <summary> /// Gets the member properties that correspond to a given path for the entity type /// </summary> /// <param name="entityType">The entity type</param> /// <param name="pathPieces">The property names from the path</param> /// <returns>The series of properties for the path</returns> public static IEnumerable <IEdmProperty> GetPropertiesForPath(this IEdmEntityType entityType, string[] pathPieces) { var currentProperties = entityType.Properties(); foreach (string propertyName in pathPieces) { IEdmProperty property = currentProperties.Single(p => p.Name == propertyName); var complexDataType = property.Type as IEdmComplexTypeReference; if (complexDataType != null) { currentProperties = complexDataType.ComplexDefinition().Properties(); } var collectionDataType = property.Type as IEdmCollectionTypeReference; if (collectionDataType != null) { var complexElementType = collectionDataType.GetCollectionItemType() as IEdmComplexTypeReference; if (complexElementType != null) { currentProperties = complexElementType.ComplexDefinition().Properties(); } } yield return(property); } }
public void GetEdmModel_WorksOnModelBuilder_WithDateTime() { // Arrange ODataModelBuilder builder = new ODataModelBuilder(); EntityTypeConfiguration <DateTimeModel> entity = builder.EntityType <DateTimeModel>(); entity.HasKey(c => c.BirthdayA); entity.Property(c => c.BirthdayB); entity.CollectionProperty(c => c.BirthdayC); entity.CollectionProperty(c => c.BirthdayD); // Act IEdmModel model = builder.GetEdmModel(); // Assert Assert.NotNull(model); IEdmEntityType entityType = Assert.Single(model.SchemaElements.OfType <IEdmEntityType>()); Assert.Equal("BirthdayA", entityType.DeclaredKey.Single().Name); IList <IEdmProperty> properties = entityType.Properties().ToList(); Assert.Equal(4, properties.Count); Assert.Equal("BirthdayA", properties[0].Name); Assert.Equal("BirthdayB", properties[1].Name); Assert.Equal("BirthdayC", properties[2].Name); Assert.Equal("BirthdayD", properties[3].Name); }
public void CanCreateEntityWithPrimitiveAndEnumKey() { // Arrange ODataModelBuilder builder = new ODataModelBuilder(); var enumEntityType = builder.EntityType <EnumModel>(); enumEntityType.HasKey(c => new { c.Simple, c.Id }); // Act IEdmModel model = builder.GetServiceModel(); // Assert IEdmEntityType entityType = model.SchemaElements.OfType <IEdmEntityType>() .FirstOrDefault(c => c.Name == "EnumModel"); Assert.NotNull(entityType); Assert.Equal(2, entityType.Properties().Count()); Assert.Equal(2, entityType.DeclaredKey.Count()); IEdmStructuralProperty enumKey = entityType.DeclaredKey.First(k => k.Name == "Simple"); Assert.Equal(EdmTypeKind.Enum, enumKey.Type.TypeKind()); Assert.Equal("Microsoft.TestCommon.Types.SimpleEnum", enumKey.Type.Definition.FullTypeName()); IEdmStructuralProperty primitiveKey = entityType.DeclaredKey.First(k => k.Name == "Id"); Assert.Equal(EdmTypeKind.Primitive, primitiveKey.Type.TypeKind()); Assert.Equal("Edm.Int32", primitiveKey.Type.Definition.FullTypeName()); }
public void GetEdmModel_CanSetDependentPropertyNullable_ForOptionalNavigation() { // Arrange ODataModelBuilder builder = new ODataModelBuilder(); EntityTypeConfiguration <User> userType = builder.EntityType <User>(); userType.HasKey(c => c.UserId).HasMany(c => c.Roles); userType.Property(u => u.StringPrincipal); EntityTypeConfiguration <Role> roleType = builder.EntityType <Role>(); roleType.HasKey(r => r.RoleId) .HasOptional(r => r.User, (r, u) => r.UserStringForeignKey == u.StringPrincipal); // Act IEdmModel model = builder.GetEdmModel(); // Assert Assert.NotNull(model); IEdmEntityType roleEntityType = model.AssertHasEntityType(typeof(Role)); roleEntityType.AssertHasNavigationProperty(model, "User", typeof(User), isNullable: true, multiplicity: EdmMultiplicity.ZeroOrOne); IEdmProperty edmProperty = Assert.Single(roleEntityType.Properties().Where(c => c.Name == "UserStringForeignKey")); Assert.True(edmProperty.Type.IsNullable); }
public void CanCreateEntityWithCompoundEnumKeys() { // Arrange ODataModelBuilder builder = new ODataModelBuilder(); var enumEntityType = builder.EntityType <EnumModel>(); enumEntityType.HasKey(c => new { c.Simple, c.Long }); // Act IEdmModel model = builder.GetServiceModel(); // Assert IEdmEntityType entityType = model.SchemaElements.OfType <IEdmEntityType>() .FirstOrDefault(c => c.Name == "EnumModel"); Assert.NotNull(entityType); Assert.Equal(2, entityType.Properties().Count()); Assert.Equal(2, entityType.DeclaredKey.Count()); IEdmStructuralProperty simpleKey = entityType.DeclaredKey.First(k => k.Name == "Simple"); Assert.Equal(EdmTypeKind.Enum, simpleKey.Type.TypeKind()); Assert.Equal("Microsoft.AspNet.OData.Test.Common.Types.SimpleEnum", simpleKey.Type.Definition.FullTypeName()); IEdmStructuralProperty longKey = entityType.DeclaredKey.First(k => k.Name == "Long"); Assert.Equal(EdmTypeKind.Enum, longKey.Type.TypeKind()); Assert.Equal("Microsoft.AspNet.OData.Test.Common.Types.LongEnum", longKey.Type.Definition.FullTypeName()); }
/// <summary> /// Обновление сущности (свойства могут быть заданы частично, т.е. указывать можно значения только измененных свойств). /// Если сущности с заданным ключом нет в БД происходит Upsert (в соответствии со стандартом). /// </summary> /// <param name="key"> Ключ обновляемой сущности. </param> /// <param name="edmEntity">Обновляемая сущность. </param> /// <returns>Обновлённая сущность.</returns> public HttpResponseMessage Patch([FromODataUri] Guid key, [FromBody] EdmEntityObject edmEntity) { try { if (key == null) { throw new ArgumentNullException("key"); } if (edmEntity == null) { edmEntity = ReplaceOdataBindNull(); } IEdmEntityType entityType = (IEdmEntityType)edmEntity.ActualEdmType; var dictionary = Request.Properties.ContainsKey(ExtendedODataEntityDeserializer.Dictionary) ? (Dictionary <string, object>)Request.Properties[ExtendedODataEntityDeserializer.Dictionary] : new Dictionary <string, object>(); foreach (var prop in entityType.Properties()) { if (!dictionary.ContainsKey(prop.Name) && edmEntity.GetChangedPropertyNames().Contains(prop.Name) && prop is EdmNavigationProperty) { return(Request.CreateResponse(System.Net.HttpStatusCode.BadRequest, "Error processing request stream. Deep updates are not supported in PUT or PATCH operations.")); } if (dictionary.ContainsKey(prop.Name) && dictionary[prop.Name] == null && (!prop.Type.IsNullable || prop.Type.IsCollection())) { return(Request.CreateResponse(System.Net.HttpStatusCode.BadRequest, $"The property {prop.Name} can not be null.")); } } DataObject obj = UpdateObject(edmEntity, key); ExecuteCallbackAfterUpdate(obj); var responseForPreferMinimal = TestPreferMinimal(); if (responseForPreferMinimal != null) { return(responseForPreferMinimal); } if (!Request.Headers.Contains("Prefer")) { return(Request.CreateResponse(System.Net.HttpStatusCode.NoContent)); } edmEntity = GetEdmObject(_model.GetEdmEntityType(type), obj, 1, null, null); var result = Request.CreateResponse(System.Net.HttpStatusCode.OK, edmEntity); result.Headers.Add("Preference-Applied", "return=representation"); return(result); } catch (Exception ex) { return(InternalServerErrorMessage(ex)); } }
private void WriteHeader(IEdmEntityType entityType) { this.headers = entityType.Properties().Where(p => p.Type.IsPrimitive()).Select(p => p.Name).ToList(); foreach (var header in this.headers) { this.context.Writer.Write("{0},", header); } this.context.Writer.WriteLine(); }
public static bool TryMatch(this KeySegment keySegment, IDictionary <string, string> mapping, IDictionary <string, object> values) { Contract.Assert(keySegment != null); Contract.Assert(mapping != null); Contract.Assert(values != null); if (keySegment.Keys.Count() != mapping.Count) { return(false); } IEdmEntityType entityType = keySegment.EdmType as IEdmEntityType; Dictionary <string, object> routeData = new Dictionary <string, object>(); foreach (KeyValuePair <string, object> key in keySegment.Keys) { string mappingName; if (!mapping.TryGetValue(key.Key, out mappingName)) { // mapping name is not found. it's not a match. return(false); } IEdmTypeReference typeReference; // get the key property from the entity type if (entityType != null) { IEdmStructuralProperty keyProperty = entityType.Key().FirstOrDefault(k => k.Name == key.Key); if (keyProperty == null) { // If it's an alternate key keyProperty = entityType.Properties().OfType <IEdmStructuralProperty>().FirstOrDefault(p => p.Name == key.Key); } Contract.Assert(keyProperty != null); typeReference = keyProperty.Type; } else { typeReference = EdmLibHelpers.GetEdmPrimitiveTypeReferenceOrNull(key.Value.GetType()); } AddKeyValues(mappingName, key.Value, typeReference, routeData, routeData); } foreach (KeyValuePair <string, object> kvp in routeData) { values[kvp.Key] = kvp.Value; } return(true); }
public static void AddKeyValueToRouteData(this RouteContext routeContext, KeySegment segment, ActionDescriptor actionDescriptor, string keyName = "key") { Contract.Assert(routeContext != null); Contract.Assert(segment != null); HttpRequest request = routeContext.HttpContext.Request; IDictionary <string, object> routingConventionsStore = request.ODataFeature().RoutingConventionsStore; IEdmEntityType entityType = segment.EdmType as IEdmEntityType; Contract.Assert(entityType != null); int keyCount = segment.Keys.Count(); foreach (var keyValuePair in segment.Keys) { bool alternateKey = false; // get the key property from the entity type IEdmStructuralProperty keyProperty = entityType.Key().FirstOrDefault(k => k.Name == keyValuePair.Key); if (keyProperty == null) { // If it's alternate key. keyProperty = entityType.Properties().OfType <IEdmStructuralProperty>().FirstOrDefault(p => p.Name == keyValuePair.Key); alternateKey = true; } Contract.Assert(keyProperty != null); // if there's only one key, just use the given key name, for example: "key, relatedKey" // otherwise, to append the key name after the given key name. // so for multiple keys, the parameter name is "keyId1, keyId2..." // for navigation property, the parameter name is "relatedKeyId1, relatedKeyId2 ..." string newKeyName; if (alternateKey || keyCount > 1) { newKeyName = keyName + keyValuePair.Key; } else { newKeyName = keyName; } // If we only have one parameter in our action which matches the type of the key required // then use the action's parameter, so if the action parameter is "productId", for example // it will still just work. if (actionDescriptor != null && keyCount == 1 && actionDescriptor.Parameters.Count == 1 && actionDescriptor.Parameters.Single().ParameterType == keyValuePair.Value.GetType()) { newKeyName = actionDescriptor.Parameters.Single().Name; } AddKeyValues(keyValuePair.Key, newKeyName, keyValuePair.Value, keyProperty.Type, routeContext.RouteData.Values, routingConventionsStore); } }
public void BuildEdmModel_WorksOnModelBuilder_ForUntypedProperty(bool convention) { // Arrange & Act IEdmModel model = null; if (convention) { ODataConventionModelBuilder builder = new ODataConventionModelBuilder(); builder.EntityType <UntypedEntity>(); model = builder.GetEdmModel(); } else { ODataModelBuilder builder = new ODataModelBuilder(); var entity = builder.EntityType <UntypedEntity>(); entity.HasKey(p => p.Id); entity.Property(p => p.Value); entity.CollectionProperty(p => p.Data); entity.CollectionProperty(p => p.Infos); model = builder.GetEdmModel(); } // Assert Assert.NotNull(model); IEdmEntityType edmEntityType = model.SchemaElements.OfType <IEdmEntityType>().First(c => c.Name == "UntypedEntity"); IEdmProperty[] edmProperties = edmEntityType.Properties().ToArray(); Assert.Equal(4, edmProperties.Length); // Value property IEdmProperty valueProperty = edmProperties.First(p => p.Name == "Value"); Assert.True(valueProperty.Type.IsNullable); // always "true"? Assert.True(valueProperty.Type.IsUntyped()); Assert.Same(EdmCoreModel.Instance.GetUntypedType(), valueProperty.Type.Definition); Assert.Equal("Edm.Untyped", valueProperty.Type.FullName()); // Data collection property IEdmProperty dataProperty = edmProperties.First(p => p.Name == "Data"); Assert.True(dataProperty.Type.IsNullable); // always "true"? Assert.True(dataProperty.Type.IsCollection()); Assert.True(dataProperty.Type.AsCollection().ElementType().IsUntyped()); Assert.Equal("Collection(Edm.Untyped)", dataProperty.Type.FullName()); // Infos collection property IEdmProperty infosProperty = edmProperties.First(p => p.Name == "Infos"); Assert.True(infosProperty.Type.IsNullable); // always "true"? Assert.True(infosProperty.Type.IsCollection()); Assert.True(infosProperty.Type.AsCollection().ElementType().IsUntyped()); Assert.Equal("Collection(Edm.Untyped)", infosProperty.Type.FullName()); }
public void LowerCamelCaser_ProcessReflectedAndExplicitPropertyNames() { // Arrange var builder = new ODataConventionModelBuilder().EnableLowerCamelCase( NameResolverOptions.ProcessReflectedPropertyNames | NameResolverOptions.ProcessExplicitPropertyNames); builder.EntitySet <LowerCamelCaserModelAliasEntity>("Entities"); // Act IEdmModel model = builder.GetEdmModel(); // Assert IEdmEntityType lowerCamelCaserEntity = Assert.Single(model.SchemaElements.OfType <IEdmEntityType>().Where(e => e.Name == "LowerCamelCaserModelAliasEntity")); Assert.Equal(4, lowerCamelCaserEntity.Properties().Count()); Assert.Single(lowerCamelCaserEntity.Properties().Where(p => p.Name == "ID")); Assert.Single(lowerCamelCaserEntity.Properties().Where(p => p.Name == "name")); Assert.Single(lowerCamelCaserEntity.Properties().Where(p => p.Name == "Something")); Assert.Single(lowerCamelCaserEntity.Properties().Where(p => p.Name == "color")); }
public void LowerCamelCaser_ProcessReflectedAndDataMemberAttributePropertyNames() { // Arrange var builder = new ODataConventionModelBuilder().EnableLowerCamelCase( NameResolverOptions.ProcessReflectedPropertyNames | NameResolverOptions.ProcessDataMemberAttributePropertyNames); EntityTypeConfiguration <LowerCamelCaserEntity> entityTypeConfiguration = builder.EntitySet <LowerCamelCaserEntity>("Entities").EntityType; entityTypeConfiguration.Property(b => b.ID).Name = "iD"; entityTypeConfiguration.Property(d => d.Name).Name = "Name"; entityTypeConfiguration.EnumProperty(d => d.Color).Name = "Something"; ComplexTypeConfiguration <LowerCamelCaserComplex> complexTypeConfiguration = builder.ComplexType <LowerCamelCaserComplex>(); complexTypeConfiguration.CollectionProperty(c => c.Notes).Name = "MyNotes"; // Act IEdmModel model = builder.GetEdmModel(); // Assert IEdmEntityType lowerCamelCaserEntity = Assert.Single(model.SchemaElements.OfType <IEdmEntityType>().Where(e => e.Name == "LowerCamelCaserEntity")); IEdmComplexType lowerCamelCaserComplex = Assert.Single(model.SchemaElements.OfType <IEdmComplexType>().Where(e => e.Name == "LowerCamelCaserComplex")); Assert.Equal(5, lowerCamelCaserEntity.Properties().Count()); Assert.Single(lowerCamelCaserEntity.Properties().Where(p => p.Name == "iD")); Assert.Single(lowerCamelCaserEntity.Properties().Where(p => p.Name == "Name")); Assert.Single(lowerCamelCaserEntity.Properties().Where(p => p.Name == "details")); Assert.Single(lowerCamelCaserEntity.Properties().Where(p => p.Name == "Something")); Assert.Single(lowerCamelCaserEntity.Properties().Where(p => p.Name == "complexProperty")); Assert.Equal(2, lowerCamelCaserComplex.Properties().Count()); Assert.Single(lowerCamelCaserComplex.Properties().Where(p => p.Name == "price")); Assert.Single(lowerCamelCaserComplex.Properties().Where(p => p.Name == "MyNotes")); }
private IEdmProperty[] GetProperties(string tableName) { if (this.metadata == null) { GetMetadata(this.odataMetadataURL); } IEdmEntityContainer defaultContainer = GetDefaultEntityContainer(this.metadata); IEdmEntitySet entitySet = defaultContainer.FindEntitySet(tableName); IEdmEntityType entityType = entitySet.ElementType; return(entityType.Properties().ToArray()); }
public void GetEdmModel_Works_WithMultiForeignKeys() { // Arrange ODataModelBuilder builder = new ODataModelBuilder(); EntityTypeConfiguration <MultiUser> userType = builder.Entity <MultiUser>(); userType.HasKey(u => new { u.UserId1, u.UserId2 }) .HasMany(u => u.Roles); EntityTypeConfiguration <MultiRole> roleType = builder.Entity <MultiRole>(); roleType.HasKey(r => r.RoleId) .HasOptional(r => r.User, (r, u) => r.UserKey1 == u.UserId1 && r.UserKey2 == u.UserId2) .CascadeOnDelete(); // Act IEdmModel model = builder.GetEdmModel(); // Assert Assert.NotNull(model); IEdmEntityType roleEntityType = model.AssertHasEntityType(typeof(MultiRole)); IEdmNavigationProperty usersNav = roleEntityType.AssertHasNavigationProperty(model, "User", typeof(MultiUser), true, EdmMultiplicity.ZeroOrOne); Assert.Equal(EdmOnDeleteAction.Cascade, usersNav.OnDelete); Assert.Equal(2, usersNav.DependentProperties.Count()); Assert.Equal("UserKey1", usersNav.DependentProperties.First().Name); Assert.Equal("UserKey2", usersNav.DependentProperties.Last().Name); IEdmProperty edmProperty = Assert.Single(roleEntityType.Properties().Where(c => c.Name == "UserKey1")); Assert.False(edmProperty.Type.IsNullable); edmProperty = Assert.Single(roleEntityType.Properties().Where(c => c.Name == "UserKey2")); Assert.False(edmProperty.Type.IsNullable); }
public void GetEdmModel_WorksOnModelBuilder_ForOpenEntityType() { // Arrange ODataModelBuilder builder = new ODataModelBuilder(); EntityTypeConfiguration <SimpleOpenEntityType> entity = builder.EntityType <SimpleOpenEntityType>(); entity.HasKey(c => c.Id); entity.Property(c => c.Name); entity.HasDynamicProperties(c => c.DynamicProperties); // Act IEdmModel model = builder.GetEdmModel(); // Assert Assert.NotNull(model); IEdmEntityType entityType = Assert.Single(model.SchemaElements.OfType <IEdmEntityType>()); Assert.True(entityType.IsOpen); Assert.Equal(2, entityType.Properties().Count()); Assert.True(entityType.Properties().Where(c => c.Name == "Id").Any()); Assert.True(entityType.Properties().Where(c => c.Name == "Name").Any()); }
private EntityInstance CreateEntityInstance(IEdmEntityType edmEntityType) { EntityInstance entity = new EntityInstance(edmEntityType.FullName(), false); foreach (var property in edmEntityType.Properties()) { if (!(property is IEdmNavigationProperty)) { entity.Property(this.BuildProperty(property)); } } return(entity); }
private void ReadEntityType(IEdmEntityType entityType) { if (IsIgnored(entityType)) return; var typeUri = GetUriMapping(entityType); var identifierPrefix = GetIdentifierPrefix(entityType); _typeUriMap[entityType.FullName()] = new TypeMapping { Uri = typeUri, IdentifierPrefix = identifierPrefix }; foreach (IEdmProperty property in entityType.Properties()) { ReadProperty(entityType, property); } }
private void CompareEntityType(IEdmEntityType expectedEntityType, IEdmEntityType actualEntityType) { this.SatisfiesEquals(expectedEntityType.FullName(), actualEntityType.FullName(), "EntityType name does not match."); this.SatisfiesEquals(expectedEntityType.IsAbstract, actualEntityType.IsAbstract, "IsAbstract does not match for EntityType '{0}'.", expectedEntityType.FullName()); string expectedBaseTypeName = expectedEntityType.BaseType != null ? ((IEdmSchemaElement)expectedEntityType.BaseType).FullName() : null; string actualBaseTypeName = actualEntityType.BaseType != null ? ((IEdmSchemaElement)actualEntityType.BaseType).FullName() : null; this.SatisfiesEquals(expectedBaseTypeName, actualBaseTypeName, "BaseType does not match for EntityType '{0}'.", expectedEntityType.FullName()); this.CompareProperties(expectedEntityType.StructuralProperties().Cast<IEdmProperty>(), actualEntityType.StructuralProperties().Cast<IEdmProperty>()); this.CompareProperties(expectedEntityType.Key().OfType<IEdmProperty>(), actualEntityType.Key().OfType<IEdmProperty>()); this.CompareNavigationProperty(expectedEntityType.Properties().OfType<IEdmNavigationProperty>(), actualEntityType.Properties().OfType<IEdmNavigationProperty>()); this.CompareTermAnnotations(expectedEntityType, actualEntityType); }
private static string GetKeyInfos(int keyCount, string keyName, IEdmEntityType entityType, string keyPrefix, out IEdmTypeReference keyType) { Contract.Assert(keyName != null); Contract.Assert(entityType != null); string newKeyName; IEdmStructuralProperty keyProperty; if (String.IsNullOrEmpty(keyName)) { Contract.Assert(keyCount == 1); keyProperty = entityType.Key().First(); newKeyName = keyPrefix; } else { bool alternateKey = false; keyProperty = entityType.Key().FirstOrDefault(k => k.Name == keyName); if (keyProperty == null) { // If it's alternate key. keyProperty = entityType.Properties().OfType<IEdmStructuralProperty>().FirstOrDefault(p => p.Name == keyName); alternateKey = true; } Contract.Assert(keyProperty != null); // if there's only one key, just use the given prefix name, for example: "key, relatedKey" // otherwise, to append the key name after the given prefix name. // so for multiple keys, the parameter name is "keyId1, keyId2..." // for navigation property, the parameter name is "relatedKeyId1, relatedKeyId2 ..." // for alternate key, to append the alternate key name after the given prefix name. if (alternateKey || keyCount > 1) { newKeyName = keyPrefix + keyName; } else { newKeyName = keyPrefix; } } keyType = keyProperty.Type; return newKeyName; }