Retrieve a record explicitely asynchronous with an ExecuteCompleted event.


LightSwitch hides for us the (async) details of a Ria service call, for which many thanks in 98% of the cases.

Once in a while, probably because you are doing something tricky (maybe in a custom control), you would like to do it in a manner closer to the RIA way.



Imagine we have a Customer entity. Following code will retrieve the customer with Id = 1 in an async way and the result we available in the ExecuteCompleted event.

int customerId = 1;
ICreateScalarQueryMethodInvocation query
                = this.DataWorkspace.ApplicationData.Details.Methods["Customers_Single"]
                .CreateInvocation(customerId) as ICreateScalarQueryMethodInvocation;

query.ExecuteCompleted += new EventHandler<ExecuteCompletedEventArgs>((s, e) =>

                Customer result = query.Result as Customer;


Note that when the ExecuteCompleted event is raised, we effectively have the data at our disposal, so we are not dealing here we deferred execution on Linq level. You can verify this by adding following code server side:

 partial void Customers_Single_PreprocessQuery(int? Id, ref IQueryable<Customer> query)

This will emulate a “heavy” query. Put a breakpoint inside the ExecuteCompleted event and press F5. You can now verify that when the processing enters the ExecutedCompletedEvent you have access to the data immediately.


Probably my shortest blog post ever since :)