diff --git a/src/EFCore.InMemory/Query/Internal/InMemoryExpressionTranslatingExpressionVisitor.cs b/src/EFCore.InMemory/Query/Internal/InMemoryExpressionTranslatingExpressionVisitor.cs index 61f3551e3f8..81803b46672 100644 --- a/src/EFCore.InMemory/Query/Internal/InMemoryExpressionTranslatingExpressionVisitor.cs +++ b/src/EFCore.InMemory/Query/Internal/InMemoryExpressionTranslatingExpressionVisitor.cs @@ -888,8 +888,10 @@ protected override Expression VisitMethodCall(MethodCallExpression methodCallExp if (methodCallExpression.Object != null && @object!.Type.IsNullableType() && methodCallExpression.Method.Name != nameof(Nullable.GetValueOrDefault) - && (!@object!.Type.IsNullableValueType() - || methodCallExpression.Method.Name != nameof(Nullable.ToString))) + && !(@object!.Type.IsNullableValueType() + && methodCallExpression.Method.Name == nameof(Nullable.ToString) + && methodCallExpression.Method.DeclaringType != null + && methodCallExpression.Method.DeclaringType.IsNullableType())) { var result = (Expression)methodCallExpression.Update( Expression.Convert(@object, methodCallExpression.Object.Type), diff --git a/test/EFCore.InMemory.FunctionalTests/Query/GearsOfWarQueryInMemoryTest.cs b/test/EFCore.InMemory.FunctionalTests/Query/GearsOfWarQueryInMemoryTest.cs index 6ec5a0a431d..d528392a152 100644 --- a/test/EFCore.InMemory.FunctionalTests/Query/GearsOfWarQueryInMemoryTest.cs +++ b/test/EFCore.InMemory.FunctionalTests/Query/GearsOfWarQueryInMemoryTest.cs @@ -147,4 +147,28 @@ public override Task Join_include_conditional(bool async) // Right join not supported in InMemory public override Task Correlated_collections_on_RightJoin_with_predicate(bool async) => AssertTranslationFailed(() => base.Correlated_collections_on_RightJoin_with_predicate(async)); + + [ConditionalTheory] + [MemberData(nameof(IsAsyncData))] + public virtual Task Select_ToString_on_non_nullable_property_of_an_optional_entity(bool async) + { + return AssertQuery( + async, + ss => ss.Set().Select(x => new + { + Id = x.Id, + SquadIdString = x.Gear.SquadId.ToString() + }), + ss => ss.Set().Select(x => new + { + Id = x.Id, + SquadIdString = x.Gear == null ? null : x.Gear.SquadId.ToString() + }), + elementSorter: e => e.Id, + elementAsserter: (e, a) => + { + AssertEqual(e.Id, a.Id); + AssertEqual(e.SquadIdString, a.SquadIdString); + }); + } }