File tree Expand file tree Collapse file tree 3 files changed +26
-1
lines changed Expand file tree Collapse file tree 3 files changed +26
-1
lines changed Original file line number Diff line number Diff line change @@ -264,6 +264,7 @@ public void ShouldNotRangeCheckNullableToNonNullableValues()
264264 string plan = Mapper . GetPlanFor < PublicField < int ? > > ( ) . ToANew < PublicField < int > > ( ) ;
265265
266266 plan . ShouldNotContain ( "int.MinValue" ) ;
267+ plan . ShouldNotContain ( "Value.HasValue" ) ;
267268 }
268269
269270 [ Fact ]
Original file line number Diff line number Diff line change @@ -156,7 +156,19 @@ public static Expression GetValueOrDefaultCall(this Expression nullableExpressio
156156
157157 [ DebuggerStepThrough ]
158158 public static Expression GetConversionTo ( this Expression expression , Type targetType )
159- => ( expression . Type != targetType ) ? Expression . Convert ( expression , targetType ) : expression ;
159+ {
160+ if ( expression . Type == targetType )
161+ {
162+ return expression ;
163+ }
164+
165+ if ( expression . Type . GetNonNullableType ( ) == targetType )
166+ {
167+ return expression . GetValueOrDefaultCall ( ) ;
168+ }
169+
170+ return Expression . Convert ( expression , targetType ) ;
171+ }
160172
161173 public static Expression WithToArrayCall ( this Expression enumerable , Type elementType )
162174 {
Original file line number Diff line number Diff line change @@ -151,6 +151,11 @@ protected override Expression VisitMethodCall(MethodCallExpression methodCall)
151151 if ( ( methodCall . Object != _mappingDataObject ) &&
152152 ( methodCall . Method . DeclaringType != typeof ( IMappingData ) ) )
153153 {
154+ if ( IsNullableGetValueOrDefaultCall ( methodCall ) )
155+ {
156+ AddExistingNullCheck ( methodCall . Object ) ;
157+ }
158+
154159 AddStringMemberAccessSubjectIfAppropriate ( methodCall . Object ) ;
155160 AddInvocationIfNecessary ( methodCall ) ;
156161 AddMemberAccessIfAppropriate ( methodCall ) ;
@@ -159,6 +164,13 @@ protected override Expression VisitMethodCall(MethodCallExpression methodCall)
159164 return base . VisitMethodCall ( methodCall ) ;
160165 }
161166
167+ private static bool IsNullableGetValueOrDefaultCall ( MethodCallExpression methodCall )
168+ {
169+ return ( methodCall . Object != null ) &&
170+ ( methodCall . Method . Name == "GetValueOrDefault" ) &&
171+ ( methodCall . Object . Type . IsNullableType ( ) ) ;
172+ }
173+
162174 private void AddExistingNullCheck ( Expression checkedAccess )
163175 {
164176 _nullCheckSubjects . Add ( checkedAccess . ToString ( ) ) ;
You can’t perform that action at this time.
0 commit comments