Stan
Stan

Reputation: 26511

Does MongoDb C# driver works with LINQ and dynamic documents?

I am wondering if I can even use LINQ on mongo documents that are not mapped and are fully dynamic. Reason for this is that I have ITEM aggrigator that holds unknown keys and values. This is only reason why I picked no-sql solution in the first place because EAV+SQL seems slow and overkill.

I inserted over 1m documents into my test collection that has one to ten fields with random data in it. Now I'm trying to get it back and using native Mongo queries it works, of course. Not so much using LINQ. Am I doing something wrong here?

Error

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

Additional information: Input string was not in a correct format.

Code

private static List<BsonDocument> Get(string query)
{
    var client = new MongoClient("mongodb://localhost");
    var server = client.GetServer();
    var db = server.GetDatabase("test");
    var collection = db.GetCollection("items");
    var collectionQuery = collection.AsQueryable();
    
    var result = collection.Find(Query.EQ("Six", 7962)).ToList(); // THIS WORKS
    //var result = collection.AsQueryable().Where(x => x["Six"] == 7962).ToList(); // ERROR

    return result;
}

Upvotes: 5

Views: 2551

Answers (2)

Captain Whippet
Captain Whippet

Reputation: 2223

It looks like version 1.10.0 of the driver supports dynamic documents in LINQ queries. That is, I have been able to execute queries like this:

        var collection = database.GetCollection("items");
        var query =
            from e in collection.AsQueryable()
            where e["string_property"] == "a_value"
            select e;

        foreach (var c in query)
        {
            Console.WriteLine(c["another_property"]);
        }

The official documentation C# Driver LINQ Tutorial only seems to include examples that use domain objects and is based on version 1.8.

The above code works in 1.10.0. I have not been able to ascertain when exactly support for the above code was added to the driver.

Upvotes: 0

i3arnon
i3arnon

Reputation: 116586

The driver does not currently support dynamic types. Here's the jira ticket for it: https://jira.mongodb.org/browse/CSHARP-539

There's also an an interesting post about some possible workaround: http://roysvork.wordpress.com/2013/04/22/using-linq-to-query-loosely-typed-data-in-mongodb/

Upvotes: 3

Related Questions