diff --git a/src/Microsoft.OpenApi.OData.Reader/Generator/OpenApiSchemaGenerator.cs b/src/Microsoft.OpenApi.OData.Reader/Generator/OpenApiSchemaGenerator.cs index 217789b5..80a37949 100644 --- a/src/Microsoft.OpenApi.OData.Reader/Generator/OpenApiSchemaGenerator.cs +++ b/src/Microsoft.OpenApi.OData.Reader/Generator/OpenApiSchemaGenerator.cs @@ -430,9 +430,22 @@ private static OpenApiSchema CreateStructuredTypeSchema(this ODataContext contex OpenApiDiscriminator discriminator = null; if (context.Settings.EnableDiscriminatorValue && derivedTypes.Any() && structuredType.BaseType != null) { + string v3RefIdentifier = new OpenApiSchema + { + Reference = new OpenApiReference + { + Type = ReferenceType.Schema, + Id = structuredType.FullTypeName() + } + }.Reference.ReferenceV3; + discriminator = new OpenApiDiscriminator { - PropertyName = "@odata.type" + PropertyName = "@odata.type", + Mapping = new Dictionary + { + {"#" + structuredType.FullTypeName(), v3RefIdentifier } + } }; } diff --git a/test/Microsoft.OpenAPI.OData.Reader.Tests/Generator/OpenApiSchemaGeneratorTests.cs b/test/Microsoft.OpenAPI.OData.Reader.Tests/Generator/OpenApiSchemaGeneratorTests.cs index 7cf18b98..4abcf592 100644 --- a/test/Microsoft.OpenAPI.OData.Reader.Tests/Generator/OpenApiSchemaGeneratorTests.cs +++ b/test/Microsoft.OpenAPI.OData.Reader.Tests/Generator/OpenApiSchemaGeneratorTests.cs @@ -80,6 +80,52 @@ public void CreateStructuredTypeSchemaThrowArgumentNullEnumType() Assert.Throws("structuredType", () => context.CreateStructuredTypeSchema(structuredType: null)); } + [Fact] + public void CreateStructuredTypeSchemaWithDiscriminatorValueEnabledReturnsCorrectSchema() + { + // Arrange + IEdmModel model = EdmModelHelper.GraphBetaModel; + ODataContext context = new(model, new OpenApiConvertSettings + { + EnableDiscriminatorValue = true, + }); + + IEdmEntityType entity = model.SchemaElements.OfType().First(t => t.Name == "directoryObject"); + Assert.NotNull(entity); // Guard + + // Act + var schema = context.CreateStructuredTypeSchema(entity); + string json = schema.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0); + + // Assert + Assert.NotNull(json); + Assert.Equal(@"{ + ""allOf"": [ + { + ""$ref"": ""#/components/schemas/microsoft.graph.entity"" + }, + { + ""title"": ""directoryObject"", + ""type"": ""object"", + ""properties"": { + ""deletedDateTime"": { + ""pattern"": ""^[0-9]{4,}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]([.][0-9]{1,12})?(Z|[+-][0-9][0-9]:[0-9][0-9])$"", + ""type"": ""string"", + ""format"": ""date-time"", + ""nullable"": true + } + }, + ""discriminator"": { + ""propertyName"": ""@odata.type"", + ""mapping"": { + ""#microsoft.graph.directoryObject"": ""#/components/schemas/microsoft.graph.directoryObject"" + } + } + } + ] +}".ChangeLineBreaks(), json); + } + [Fact] public void CreateComplexTypeWithoutBaseSchemaReturnCorrectSchema() {