How can I load second degree entity relations with a WCF data service?
I am trying to query a single entity in a database with a DataServiceQuery. The entity I am trying to load has relations to a graph of other entities that I want to load as well. MSDN describes here and here that I can load my referred entities using either DataServiceQuery<TElement>.Expand or DataServiceContext.LoadProperty.
开发者_开发问答This works fine for first degree relations of my entity, but I have a problem loading relations of relations.
Obviously I could call LoadProperty for all second degree relations and loop through all second degree collections, but I was hoping that I could eager load the whole relation graph in a single query. Is that possible?
Edit
Actually loading the second degree relations is not that obvious after all. The following code fails (domain model changed for clarity):
var context = DataServiceReference.DataServiceContextFactory.Create();
var customer = (from c in context.Customers.Expand("Orders")
where c.CustomerId.Equals(customerId)
select c).First();
foreach (var order in customer.Orders)
{
context.LoadProperty(order, "Products");
The last line above throws InvalidOperationException: "The context is not currently tracking the entity.". I use self-tracking-entities. Could this error be related to STE?
How would I load second degree relations in any way?
Solution edit
It turns out that DataServiceQuery<TElement>.Expand uses a different path syntax compared to ObjectQuery<T>.Include. The former uses slash as path separator the latter uses dot. Can anyone explain why the syntax is inconsistent and where I can find documentation of the Expand path syntax?
The DataServiceContextFactory is your own class, right? (since that's not how you typically instantiate a DataServiceContext). Assuming it ends up creating a normal DataServiceContext instance then the way to eager load multiple levels is just to specify the multiple levels in you Expand call. So for example: context.Customers.Expand("Orders/Products") Will return you all customers, their orders and all the products for those orders. For LoadProperty to work, please make sure that on your DataServiceContext the property MergeOption is set to one of the options which allow tracking. Note that the client side tracking has nothing to do with the server side EF tracking (it's a separate code on a separate machine technically). You can verify that the context tracks the entity in question by trying to call context.GetEntityDescriptor(myEntityInstance) If it returns non-null, the context is tracking the entity and LoadProperty should work.
精彩评论