After discussing my previous post with Philip Freeman, he suggested another good example would be to show how to use Linq Query Expression Syntax with RIA Domain Context calls. To help facilitate this example I created two new Extension Methods; LoadEntityWithRx and LoadEntitiesWithRx .
Load Entity With Rx
Here we are only interested in a single Entity returned by the Load operation of the domain context. This Extension Method follows the same pattern as the ones on the previous blog post. The Load operation is called (line 5) on the Domain Context, and the work is done by the ReturnEntity method. Because nothing needs to be done on unsubscription, an empty Action is returned.
This is where the work is done; we either pass the exception along to the Observer or pass the Entity along. More work should be done to handle missing Entities (line 10); here I assume there will be exactly one Entity returned, which is not always the case.
Another good side effect of using the Extension Methods is you can consolidate your Error Handling for Domain Service calls.
Load Entities With Rx
The same pattern is followed with the LoadEntityWithRx Extension Method. The work is being done with the ReturnEntities method.
A similar pattern is followed here as well, where Exceptions are passed to the Observer, and the OnNext method is called to pass along the Entities.
Query Expression Syntax Example
In this example I have created are really bad model for Customer and Orders.
If you want to Load an Entity i.e. a Customer and then you want to take data from that Entity i.e. Customer Id, and Load another Entity the nested callbacks can get really ugly (example below). I will show how it works with Linq Query Expression Syntax, and then I will show how it would be done normally.
In the example above you can reason about what the code is doing. First query on user name of “Fred” (Lind 5) then get the Customers Id (Line 8), then Query on the Orders matching that Customer Id (Line 9). Finally it is returning to the subscriber as an Anonymous Type containing the Customer object and its Orders (Line 10).
Here the same result is accomplished, but it is so much harder to reason about the code. Imagine if you had to maintain this code. I have seen a lot of production code where the developer used 5+ nested callbacks; not fun. Maintaining the first code sample will be so much easier.
The same code is being called, but with some well-placed Extension Methods we can use the power and ease of Linq Query Expression Syntax to make code more maintainable.