From e7c2faff3200795c40b7c76c25e3e421e667d0ba Mon Sep 17 00:00:00 2001 From: Pranav K Date: Fri, 27 Jun 2014 15:03:51 -0700 Subject: [PATCH] Unwrap nullable types in PropertyHelper prior to looking up properties Fixes #721 --- .../PropertyHelper.cs | 4 +++ .../PropertyHelperTest.cs | 32 +++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/src/Microsoft.AspNet.Mvc.Common/PropertyHelper.cs b/src/Microsoft.AspNet.Mvc.Common/PropertyHelper.cs index 666ec7a3c2..2f2c9c9a4f 100644 --- a/src/Microsoft.AspNet.Mvc.Common/PropertyHelper.cs +++ b/src/Microsoft.AspNet.Mvc.Common/PropertyHelper.cs @@ -198,6 +198,10 @@ namespace Microsoft.AspNet.Mvc Func createPropertyHelper, ConcurrentDictionary cache) { + // Unwrap nullable types. This means Nullable.Value and Nullable.HasValue will not be + // part of the sequence of properties returned by this method. + type = Nullable.GetUnderlyingType(type) ?? type; + // Using an array rather than IEnumerable, as target will be called on the hot path numerous times. PropertyHelper[] helpers; diff --git a/test/Microsoft.AspNet.Mvc.Core.Test/PropertyHelperTest.cs b/test/Microsoft.AspNet.Mvc.Core.Test/PropertyHelperTest.cs index a7b7765279..e9cc7ae89d 100644 --- a/test/Microsoft.AspNet.Mvc.Core.Test/PropertyHelperTest.cs +++ b/test/Microsoft.AspNet.Mvc.Core.Test/PropertyHelperTest.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System; using System.Linq; using System.Reflection; using Xunit; @@ -114,6 +115,32 @@ namespace Microsoft.AspNet.Mvc Assert.Equal("Prop6", helper.Name); } + [Theory] + [InlineData(typeof(int?))] + [InlineData(typeof(DayOfWeek?))] + public void PropertyHelper_WorksForNullablePrimitiveAndEnumTypes(Type nullableType) + { + // Act + var properties = PropertyHelper.GetProperties(nullableType); + + // Assert + Assert.Empty(properties); + } + + [Fact] + public void PropertyHelper_UnwrapsNullableTypes() + { + // Arrange + var myType = typeof(MyStruct?); + + // Act + var properties = PropertyHelper.GetProperties(myType); + + // Assert + var property = Assert.Single(properties); + Assert.Equal("Foo", property.Name); + } + [Fact] public void PropertyHelper_WorksForStruct() { @@ -350,5 +377,10 @@ namespace Microsoft.AspNet.Mvc public static string NotVisible4 { get; set; } } + + private struct MyStruct + { + public string Foo { get; set; } + } } }