What are the alternatives to using Expand in a LINQ to ADO.net Data Service Query?

entity-framework lazy-loading linq wcf-data-services

Question

I am wondering if there are any alternatives to using the Expand key word when performing an LINQ to ADO.net Data Services query. The expand method does get me the data I am interested in, but it requires me to know all of the sub-objects that I am going to be working with in advance. My absolute preference would be that those sub-objects would be lazy loaded for me when I access them, but this doesn't look to be an option (I could add this lazy loading to the get on that sub-object property, but it gets wiped out when I do an update of the data service reference).

Does anyone have any suggestions/best practices/alternatives for this situation? Thanks.

===== Example Code using Member that has a MailingAddress =====

Works:

var me = (from m in ctx.Member.Expand("MailingAddress")
          where m.MemberID == 10000
          select m).First();
MessageBox.Show(me.MailingAddress.Street);

Would Prefer (would really like if this then went and loaded the MailingAddress)

var me = (from m in ctx.Member
          where m.MemberID == 10000
          select m).First();
MessageBox.Show(me.MailingAddress.Street);

Or at least (note: something similar to this, with MailingAddressReference, works on the server side if I do so as LINQ to Entities in a Service Operation)

var me = (from m in ctx.Member
          where m.MemberID == 10000
          select m).First();
if (!(me.MailingAddress.IsLoaded())) me.MailingAddress.Load()
MessageBox.Show(me.MailingAddress.Street);

Accepted Answer

Loading sub-objects via ADO.net Data Services seem to have two choices:

Eager Loading

Accomplished by .Expand("[MemberVariableName]") on the LINQ to Data Services example

var me = (from m in ctx.Member.Expand("MailingAddress")          
         where m.MemberID == 10000          
         select m).First();
MessageBox.Show(me.MailingAddress.Street);

Lazy Loading

Accomplished by calling .LoadProperty on the context and passing it the variable and the property that should be lazy loaded.

var me = (from m in ctx.Member          
          where m.MemberID == 10000          
          select m).First();
ctx.LoadProperty(myMember, "MailingAddresses");
MessageBox.Show(me.MailingAddress.Street);

Popular Answer

With LINQ to Entities you can also use the Include method. You can apply this to me after it's declared but before it's executed, e.g.:

me = me.Include("MailingAddress");


Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow