Fun with NoRM 2
This second post in “Fun With NoRM” will be about querying…
How to get everything
Querying collections can be done easily with the anonymous types of C# 3 – e.g. the Order collection from my previous post can be queried for all orders like so:
var orders = mongo.GetCollection<Order>(); var allOrders = orders.Find();
How to use criteria
If we’re looking for some particular order, we can query by field values like so:
var orderNumber2 = orders.Find(new { Number = 2 });
or by using the query operators residing in the static class Q:
var ordersWithNumberGreaterThan2 = orders.Find(new { Number = Q.GreaterThan(2) });
More advanced criteria
The query operators can even be combined by combining criteria like so:
var ordersWithNumberBetween5And10 = orders.Find(new { Number = Q.GreaterThan(5).And.LessThan(10) });
Now, what about the nifty dot notation? This an example where C#’s capabilities don’t cut it anymore, as everything on the left side in an anonymous type need to be valid identifiers – so no dots in property names!
This is solved in NoRM by introducing Expando! (not to be confused with ExpandoObject of .NET 4, even though they have similarities…)
Expando is just a dictionary, so to query by the field of an embedded object, do it like so:
var q = new Expando(); q["Items.Name"] = "beer"; var ordersWithBeer = orders.Find(q);
As you can see, querying with NoRM is pretty easy – and I think the NoRM guys have found a pretty decent workaround in the case of dot notation, where C#’s syntax could not be bent further.
Stay tuned for more posts…