I am storing documents in MongoDB, represented by the following class:
public class Entity
{
public string Id;
public string Name;
public List<EntityAttribute> Attributes = new List<EntityAttribute>();
}
public class EntityAttribute
{
public string Key;
public object Value;
public string DataType;
}
The "Value" object on "EntityAttribute" can obviously be any type of object (string, int, float, etc), and that is the intention.
When my app attempts to perform a query using a relational operator, such as "<" or ">", it will cast the "EntityAttribute.Value" object to the appropriate type (in order to use a relational operator). The following is an example:
var results = entities.AsQueryable<Entity>()
.Where(x => x.Type == "dogs" &&
x.Attributes.Any(a => a.Key == "age" && (int)a.Value > 5)).ToList();
This produces the following exception:
Unsupported where clause: ((Int32)a.Value > 5).
I am using the MongoDB CSharp Linq driver (http://docs.mongodb.org/ecosystem/tutorial/use-linq-queries-with-csharp-driver/). My assumption is that casting is not supported. Is this the case?
As a comparison, this same type of syntax (linq query) does work within RavenDB's LINQ driver, which is:
var results = session.Query<Entity>()
.Where(x => x.Type == "dogs")
.Intersect()
.Where(x => x.Attributes.Any(a => a.Key == "age" && (int)a.Value > 5)).ToList();
Is there any way to accomplish this, via LINQ, using the MongoDB CSharp LINQ Driver?
I can get all required queries to work using Query.EQ, Query.GT, and Query.LT, though I would rather use LINQ if possible.
You are correct that LINQ queries of this form (downcasting a field of type object to a more concrete class in order to do a comparison) are not currently supported by the C# driver.
I've created a JIRA ticket requesting this feature. See:
https://jira.mongodb.org/browse/CSHARP-900
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With