Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
* limitations under the License.
*/

using System;
using System.Linq.Expressions;
using MongoDB.Driver.Linq.Linq3Implementation.Ast.Filters;
using MongoDB.Driver.Linq.Linq3Implementation.ExtensionMethods;
Expand Down Expand Up @@ -72,6 +73,14 @@ private static AstFilter Translate(TranslationContext context, Expression expres

var fieldTranslation = ExpressionToFilterFieldTranslator.Translate(context, fieldExpression);
var value = valueExpression.GetConstantValue<object>(containingExpression: expression);

var serializerValueType = fieldTranslation.Serializer.ValueType;
if (value != null && !serializerValueType.IsInstanceOfType(value))
{
var targetType = Nullable.GetUnderlyingType(serializerValueType) ?? serializerValueType;
value = Convert.ChangeType(value, targetType);
Copy link

Copilot AI May 1, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new Convert.ChangeType call can throw (InvalidCastException/OverflowException/FormatException) and will currently bubble out of translation without context. Please catch conversion failures here and rethrow an ExpressionNotSupportedException tied to the original expression so users get a consistent LINQ translation error.

Suggested change
value = Convert.ChangeType(value, targetType);
try
{
value = Convert.ChangeType(value, targetType);
}
catch (InvalidCastException)
{
throw new ExpressionNotSupportedException(expression);
}
catch (OverflowException)
{
throw new ExpressionNotSupportedException(expression);
}
catch (FormatException)
{
throw new ExpressionNotSupportedException(expression);
}

Copilot uses AI. Check for mistakes.
}

var serializedValue = SerializationHelper.SerializeValue(fieldTranslation.Serializer, value);
return AstFilter.Eq(fieldTranslation.Ast, serializedValue);
}
Comment on lines +80 to 86
Copy link

Copilot AI May 1, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Conversion is attempted for any value/type mismatch, which can introduce unintended/culture-dependent conversions (e.g., string->number) rather than failing translation. Consider restricting this conversion to known-safe cases (e.g., numeric/char and nullable numeric via ConvertHelper/TypeExtensions) and leaving other mismatches to fail predictably.

Suggested change
var targetType = Nullable.GetUnderlyingType(serializerValueType) ?? serializerValueType;
value = Convert.ChangeType(value, targetType);
}
var serializedValue = SerializationHelper.SerializeValue(fieldTranslation.Serializer, value);
return AstFilter.Eq(fieldTranslation.Ast, serializedValue);
}
if (!TryConvertKnownSafeValue(value, serializerValueType, out value))
{
throw new ExpressionNotSupportedException(expression);
}
}
var serializedValue = SerializationHelper.SerializeValue(fieldTranslation.Serializer, value);
return AstFilter.Eq(fieldTranslation.Ast, serializedValue);
}
private static bool TryConvertKnownSafeValue(object value, Type serializerValueType, out object convertedValue)
{
var sourceType = value.GetType();
var targetType = Nullable.GetUnderlyingType(serializerValueType) ?? serializerValueType;
if (targetType.IsInstanceOfType(value))
{
convertedValue = value;
return true;
}
if (IsNumericOrCharType(sourceType) && IsNumericOrCharType(targetType))
{
convertedValue = Convert.ChangeType(value, targetType);
return true;
}
convertedValue = null;
return false;
}
private static bool IsNumericOrCharType(Type type)
{
type = Nullable.GetUnderlyingType(type) ?? type;
switch (Type.GetTypeCode(type))
{
case TypeCode.Byte:
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
case TypeCode.Char:
return true;
default:
return false;
}
}

Copilot uses AI. Check for mistakes.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
/* Copyright 2010-present MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using MongoDB.Driver.TestHelpers;
using Xunit;

namespace MongoDB.Driver.Tests.Linq.Linq3Implementation.Translators.ExpressionToFilterTranslators.MethodTranslators
{
public class EqualsMethodToFilterTranslatorTests : LinqIntegrationTest<EqualsMethodToFilterTranslatorTests.ClassFixture>
{
public EqualsMethodToFilterTranslatorTests(ClassFixture fixture) : base(fixture)
{
}

[Fact]
public void Equals_with_uint64_and_nullable_int32_should_translate()
{
var collection = Fixture.Collection;
ulong value = 2;

var queryable = collection.AsQueryable()
.Where(e => e.ReportsTo.Equals(value));

Comment on lines +37 to +39
Copy link

Copilot AI May 1, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These tests cover field.Equals(constant) but not the supported shape where the constant is the receiver (constant.Equals(field)), which exercises the translator's constant/field swapping logic with the new conversion behavior. Adding at least one test for that form would help prevent regressions.

Copilot uses AI. Check for mistakes.
var stages = Translate(collection, queryable);
AssertStages(stages, "{ $match : { ReportsTo : 2 } }");

var results = queryable.ToList();
results.Should().HaveCount(1);
results[0].Id.Should().Be(1);
}

[Fact]
public void Equals_with_int32_and_nullable_int32_should_translate()
{
var collection = Fixture.Collection;
int value = 2;

var queryable = collection.AsQueryable()
.Where(e => e.ReportsTo.Equals(value));

var stages = Translate(collection, queryable);
AssertStages(stages, "{ $match : { ReportsTo : 2 } }");

var results = queryable.ToList();
results.Should().HaveCount(1);
results[0].Id.Should().Be(1);
}

[Fact]
public void Equals_with_null_and_nullable_int32_should_translate()
{
var collection = Fixture.Collection;

var queryable = collection.AsQueryable()
.Where(e => e.ReportsTo.Equals(null));

var stages = Translate(collection, queryable);
AssertStages(stages, "{ $match : { ReportsTo : null } }");

var results = queryable.ToList();
results.Should().HaveCount(1);
results[0].Id.Should().Be(3);
}

[Fact]
public void Equals_with_string_and_nullable_int32_should_throw()
{
var collection = Fixture.Collection;
var value = "2";

var queryable = collection.AsQueryable()
.Where(e => e.ReportsTo.Equals(value));

var stages = Translate(collection, queryable);
AssertStages(stages, "{ $match : { ReportsTo : 2 } }");

var results = queryable.ToList();
results.Should().HaveCount(1);
results[0].Id.Should().Be(1);
}

[Fact]
public void Equals_with_no_match_should_return_empty()
{
var collection = Fixture.Collection;
ulong value = 999;

var queryable = collection.AsQueryable()
.Where(e => e.ReportsTo.Equals(value));

var stages = Translate(collection, queryable);
AssertStages(stages, "{ $match : { ReportsTo : 999 } }");

var results = queryable.ToList();
results.Should().BeEmpty();
}

[Fact]
public void Equals_with_overflowing_uint64_and_nullable_int32_should_throw()
{
var collection = Fixture.Collection;
ulong value = (ulong)int.MaxValue + 1;

var queryable = collection.AsQueryable()
.Where(e => e.ReportsTo.Equals(value));

var exception = Record.Exception(() => Translate(collection, queryable));
exception.Should().BeOfType<OverflowException>();
}

public class C
{
public int Id { get; set; }
public int? ReportsTo { get; set; }
}

public sealed class ClassFixture : MongoCollectionFixture<C>
{
protected override IEnumerable<C> InitialData =>
[
new C { Id = 1, ReportsTo = 2 },
new C { Id = 2, ReportsTo = 5 },
new C { Id = 3, ReportsTo = null }
];
}
}
}
Loading