Skip to content

Commit b536191

Browse files
committed
CSHARP-1509: fixing invalid cast exception for legal casts.
1 parent 8895e8c commit b536191

File tree

2 files changed

+24
-7
lines changed

2 files changed

+24
-7
lines changed

src/MongoDB.Driver.Tests/Linq/Translators/PredicateTranslatorTests.cs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -740,6 +740,16 @@ public void Not_String_IsNullOrEmpty()
740740
"{A: { $nin: [null, ''] } }");
741741
}
742742

743+
[Test]
744+
public void Binding_through_a_necessary_conversion()
745+
{
746+
long id = 10;
747+
var root = _collection.FindSync(x => x.Id == id).FirstOrDefault();
748+
749+
root.Should().NotBeNull();
750+
root.A.Should().Be("Awesome");
751+
}
752+
743753
[Test]
744754
public void Binding_through_an_unnecessary_conversion()
745755
{

src/MongoDB.Driver/Linq/Expressions/ISerializationExpression.cs

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ public static BsonValue SerializeValue(this ISerializationExpression field, obje
4848
{
4949
Ensure.IsNotNull(field, nameof(field));
5050

51-
value = ConvertEnumIfNecessary(field.Serializer.ValueType, value);
51+
value = ConvertIfNecessary(field.Serializer.ValueType, value);
5252

5353
var tempDocument = new BsonDocument();
5454
using (var bsonWriter = new BsonDocumentWriter(tempDocument))
@@ -73,7 +73,7 @@ public static BsonArray SerializeValues(this ISerializationExpression field, IEn
7373
bsonWriter.WriteStartArray();
7474
foreach (var value in values)
7575
{
76-
field.Serializer.Serialize(context, ConvertEnumIfNecessary(field.Serializer.ValueType, value));
76+
field.Serializer.Serialize(context, ConvertIfNecessary(field.Serializer.ValueType, value));
7777
}
7878
bsonWriter.WriteEndArray();
7979
bsonWriter.WriteEndDocument();
@@ -96,18 +96,25 @@ private static string CombineFieldNames(string prefix, string suffix)
9696
return prefix + "." + suffix;
9797
}
9898

99-
private static object ConvertEnumIfNecessary(Type valueType, object value)
99+
private static object ConvertIfNecessary(Type targetType, object value)
100100
{
101-
if (valueType.IsEnum || valueType.IsNullableEnum())
101+
if (targetType.IsEnum || targetType.IsNullableEnum())
102102
{
103103
if (value != null)
104104
{
105-
if (valueType.IsNullableEnum())
105+
if (targetType.IsNullableEnum())
106106
{
107-
valueType = valueType.GetNullableUnderlyingType();
107+
targetType = targetType.GetNullableUnderlyingType();
108108
}
109109

110-
value = Enum.ToObject(valueType, value);
110+
value = Enum.ToObject(targetType, value);
111+
}
112+
}
113+
else if (targetType != typeof(BsonValue) && !targetType.IsNullable())
114+
{
115+
if (value != null && targetType != value.GetType())
116+
{
117+
value = Convert.ChangeType(value, targetType);
111118
}
112119
}
113120

0 commit comments

Comments
 (0)