Skip to content

Commit 9ca9b34

Browse files
authored
Fix np(...) with UnaryExpression (#509)
1 parent 6dfec76 commit 9ca9b34

File tree

2 files changed

+44
-2
lines changed

2 files changed

+44
-2
lines changed

src/System.Linq.Dynamic.Core/Parser/ExpressionHelper.cs

+15-1
Original file line numberDiff line numberDiff line change
@@ -294,7 +294,11 @@ public bool TryGenerateAndAlsoNotNullExpression(Expression sourceExpression, boo
294294

295295
public bool ExpressionQualifiesForNullPropagation(Expression expression)
296296
{
297-
return expression is MemberExpression || expression is ParameterExpression || expression is MethodCallExpression;
297+
return
298+
expression is MemberExpression ||
299+
expression is ParameterExpression ||
300+
expression is MethodCallExpression ||
301+
expression is UnaryExpression;
298302
}
299303

300304
private Expression GetMemberExpression(Expression expression)
@@ -349,6 +353,11 @@ private List<Expression> CollectExpressions(bool addSelf, Expression sourceExpre
349353
expressionRecognized = expression != null;
350354
break;
351355

356+
case UnaryExpression unaryExpression:
357+
expression = GetUnaryExpression(unaryExpression);
358+
expressionRecognized = expression != null;
359+
break;
360+
352361
default:
353362
expressionRecognized = false;
354363
break;
@@ -374,5 +383,10 @@ private static Expression GetMethodCallExpression(MethodCallExpression methodCal
374383
// Something like: "np(MyClasses.FirstOrDefault())"
375384
return methodCallExpression.Arguments.FirstOrDefault();
376385
}
386+
387+
private static Expression GetUnaryExpression(UnaryExpression unaryExpression)
388+
{
389+
return unaryExpression.Operand;
390+
}
377391
}
378392
}

test/System.Linq.Dynamic.Core.Tests/QueryableTests.Is,OfType,As,Cast.cs

+29-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1-
using NFluent;
1+
using System.Collections.Generic;
22
using System.Linq.Dynamic.Core.Exceptions;
33
using System.Linq.Dynamic.Core.Tests.Entities;
4+
using FluentAssertions;
5+
using NFluent;
46
using Xunit;
57

68
namespace System.Linq.Dynamic.Core.Tests
@@ -175,6 +177,32 @@ public void As_Dynamic_ActingOnIt_WithType()
175177
Check.That(countAsDynamic).Equals(1);
176178
}
177179

180+
public class AS_A { }
181+
public class AS_B : AS_A
182+
{
183+
public string MyProperty { get; set; }
184+
}
185+
186+
[Fact]
187+
[Trait("bug", "452")]
188+
public void As_UnaryExpression()
189+
{
190+
// Arrange
191+
var a = new AS_A();
192+
var b = new AS_B { MyProperty = "x" };
193+
var lst = new List<AS_A>()
194+
{
195+
a,
196+
b
197+
};
198+
199+
// Act
200+
var result = lst.AsQueryable().Where($"np(as(\"{typeof(AS_B).FullName}\").MyProperty) = \"x\"");
201+
202+
// Assert
203+
result.ToDynamicArray().Should().HaveCount(1).And.Contain(b);
204+
}
205+
178206
[Fact]
179207
public void CastToType_WithType()
180208
{

0 commit comments

Comments
 (0)