From 835f080fae10ce8d651dca5cec40b2f4d4b053e6 Mon Sep 17 00:00:00 2001 From: Alexander Titov Date: Wed, 13 May 2020 11:45:11 +0300 Subject: [PATCH] Do not generate XmlElementAttribute IsNillable=true for collection property with non nullable element type For XmlSerializer IsNillable=true is for collection element ant not for collection itself. Because we do not support Nullable<> for collection elements with non nullable datatypes then we must not generate IsNillable=true. If we generate IsNillable=true for collectios with non nullable value types then XmlSerializer throws exception: 'System.InvalidOperationException: IsNullable may not be 'true' for value type System.DateTime. Please consider using Nullable instead' --- XmlSchemaClassGenerator.Tests/XmlTests.cs | 40 ++++++++++++++++++++++- XmlSchemaClassGenerator/TypeModel.cs | 2 +- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/XmlSchemaClassGenerator.Tests/XmlTests.cs b/XmlSchemaClassGenerator.Tests/XmlTests.cs index 1b3e70f0..bf4d8e90 100644 --- a/XmlSchemaClassGenerator.Tests/XmlTests.cs +++ b/XmlSchemaClassGenerator.Tests/XmlTests.cs @@ -1797,7 +1797,7 @@ public void AmbiguousAnonymousTypesTest() { GenerateNamespace = key =>key.XmlSchemaNamespace } - , }; + }; var contents = ConvertXml(nameof(GenerateXmlRootAttributeForEnumTest), new[]{xsd1, xsd2}, generator).ToArray(); Assert.Equal(2, contents.Length); @@ -1842,5 +1842,43 @@ public void AmbiguousAnonymousTypesTest() Assert.Equal("TestType2Property", xmlRootAttribute.ElementName); Assert.Equal("Test_NS2", xmlRootAttribute.Namespace); } + + [Fact] + public void TestShouldPatternForCollections() + { + const string xsd = @" + + + + + + + + + + + + + + + + "; + + var generator = new Generator + { + NamespaceProvider = new NamespaceProvider + { + GenerateNamespace = key => key.XmlSchemaNamespace + } + }; + + var contents = ConvertXml(nameof(TestShouldPatternForCollections), xsd, generator).ToArray(); + Assert.Equal(1, contents.Length); + var assembly = Compiler.Compile(nameof(GenerateXmlRootAttributeForEnumTest), contents); + var testType = assembly.GetType("Test_NS1.TestType"); + var serializer = new XmlSerializer(testType); + Assert.NotNull(serializer); + } } } diff --git a/XmlSchemaClassGenerator/TypeModel.cs b/XmlSchemaClassGenerator/TypeModel.cs index 3da80147..539673c2 100644 --- a/XmlSchemaClassGenerator/TypeModel.cs +++ b/XmlSchemaClassGenerator/TypeModel.cs @@ -1221,7 +1221,7 @@ private IEnumerable GetAttributes(bool isArray) } } - if (IsNillable) + if (IsNillable && !(IsCollection && Type is SimpleModel m && m.ValueType.IsValueType)) { attribute.Arguments.Add(new CodeAttributeArgument("IsNullable", new CodePrimitiveExpression(true))); }