[CSHARP-1509] FilterDefinitionBuilder Where can result in an InvalidCastException when filter is rendered Created: 14/Dec/15  Updated: 18/May/16  Resolved: 11/Jan/16

Status: Closed
Project: C# Driver
Component/s: Linq
Affects Version/s: 2.2
Fix Version/s: 2.2.4

Type: Bug Priority: Major - P3
Reporter: Robert Stam Assignee: Craig Wilson
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Related
related to CSHARP-1542 Using abstract type within Queryable ... Closed

 Description   

Given the following class:

public class C
{
    public int Id;
    public int Prop;
}

the following query will throw an InvalidCastException:

var builder = Builders<C>.Filter;
var value = 2067L; // note: value is a long
var filter = builder.Where(x => x.Prop == value); // note: x.Prop is an int
var document = await collection.Find(filter).FirstOrDefaultAsync();

Note: this worked in 2.0.2 but no longer works in 2.1.1+.



 Comments   
Comment by Githook User [ 17/Mar/16 ]

Author:

{u'username': u'craiggwilson', u'name': u'Craig Wilson', u'email': u'craiggwilson@gmail.com'}

Message: CSHARP-1509: fixing invalid cast exception for legal casts.
Branch: v2.2.x
https://github.com/mongodb/mongo-csharp-driver/commit/b536191a4c443abcf9eaaa58879beeb59496c757

Comment by Githook User [ 11/Jan/16 ]

Author:

{u'username': u'craiggwilson', u'name': u'Craig Wilson', u'email': u'craiggwilson@gmail.com'}

Message: CSHARP-1509: fixing invalid cast exception for legal casts.
Branch: master
https://github.com/mongodb/mongo-csharp-driver/commit/399959d69c13170a32caa93dd347dc8689f68ed3

Comment by Robert Stam [ 14/Dec/15 ]

Possible workarounds in the meantime:

1. Declare value as an int so that it matches the type of x.Prop
2. Declare x.Prop as a long so that it matches the type of value
3. Cast value to an int in the query

The third option looks like this:

var filter = builder.Where(x => x.Prop == (int)value);

Note that the third option might match unexpected documents if casting value to an int requires truncating because the value doesn't fit in 32 bits.

Generated at Wed Feb 07 21:39:48 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.