How can we avoid the extra round trips?

 Posted by ArticlesMaint on 9/29/2009 | Category: LINQ Interview questions | Views: 2159


We can instruct LINQ engine to load all the objects using ‘DataLoadOptions’. Below are the steps involved to enable ‘DataLoadOptions’.

The first step is to create the data context class.
 

DataContext objContext = new DataContext(strConnectionString);


 


Second step is to create the ‘DataLoadOption’ object.
 

DataLoadOptions objDataLoadOption = new DataLoadOptions();


 


Using the LoadWith method we need to define that we want to load customer with address in one SQL.



objDataLoadOption.LoadWith<clsCustomerWithAddresses>(clsCustomerWithAddresses => clsCustomerWithAddresses.Addresses);

 


Every address object has phone object , so we have also defined saying that the phone objects should be loaded for every address object in one SQL.
 

objDataLoadOption.LoadWith<clsAddresses>(clsAddresses => clsAddresses.Phone);


 


Whatever load option you have defined you need to set the same to the data context object using ‘LoadOptions’ property.
 

objContext.LoadOptions = objDataLoadOption;


 


Finally prepare you query.
 

var MyQuery = from objCustomer in objContext.GetTable<clsCustomerWithAddresses>()

select objCustomer;

 


Start looping through the objects.


foreach (clsCustomerWithAddresses objCustomer in MyQuery)
{

Response.Write(objCustomer.CustomerName + "<br>");

foreach (clsAddresses objAddress in objCustomer.Addresses)
{
Response.Write("===Address:- " + objAddress.Address1 + "<br>");
Response.Write("========Mobile:- " + objAddress.Phone.MobilePhone + "<br>");
Response.Write("========LandLine:- " + objAddress.Phone.LandLine + "<br>");
}
}


 


Below is the complete source code for the same.
 

DataContext objContext = new DataContext(strConnectionString);

DataLoadOptions objDataLoadOption = new DataLoadOptions();
objDataLoadOption.LoadWith<clsCustomerWithAddresses>(clsCustomerWithAddresses => clsCustomerWithAddresses.Addresses);
objDataLoadOption.LoadWith<clsAddresses>(clsAddresses => clsAddresses.Phone);
objContext.LoadOptions = objDataLoadOption;
var MyQuery = from objCustomer in objContext.GetTable<clsCustomerWithAddresses>()
select objCustomer;

foreach (clsCustomerWithAddresses objCustomer in MyQuery)
{

Response.Write(objCustomer.CustomerName + "<br>");

foreach (clsAddresses objAddress in objCustomer.Addresses)
{
Response.Write("===Address:- " + objAddress.Address1 + "<br>");
Response.Write("========Mobile:- " + objAddress.Phone.MobilePhone + "<br>");
Response.Write("========LandLine:- " + objAddress.Phone.LandLine + "<br>");
}
}


 


Abracadabra…. Now if you run the code LINQ has executed only one SQL with proper joins as compared to 3 SQL for every object shown previously.
 



Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response