Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
like image 399
ChrisHDog Avatar asked Oct 07 '08 07:10

ChrisHDog


2 Answers

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);
like image 144
ChrisHDog Avatar answered Oct 05 '22 00:10

ChrisHDog


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");
like image 37
Craig Stuntz Avatar answered Oct 04 '22 23:10

Craig Stuntz