5

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.

1
  • I think the problem could be that your query can not be translated to a MongoDB query. Have you checked if it wokrs without the cast (int)? You could find a comparission between different types, but you can solve this problem by adding a new filter by datatype (you already have that field in your EntityAttribute class) Commented Jan 23, 2014 at 8:04

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

Is there any where to run queries on ExpandoObjects? Surely they need to be casted right?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.