all things Sitecore related

Linq to Sql: Retrieve properties from related data (LoadWith)

By on January 15, 2009 in ASP.Net, linq, SQL Server with 0 Comments

You have to specify which related-data you want to retrieve from a object so you can access them outside the Linq data-context. You can achieve this by using the LoadWith method of the DataLoadOptions Class. The LoadWith method accepts an lambda expression that specifies which object you want to retrieve.

In the following example I have a employee table that has a relation with the company table. In my code I want to show the employee with the company name (outside the DataContext).


Employee employee;

using (LinqDataContext db = new (LinqDataContext())
{
   DataLoadOptions dlo = new DataLoadOptions(); 
   dlo.LoadWith<Employee>(e => e.Company);
   db.LoadOptions = dlo;

   employee = from item in db.Employees
                      select item).First<Employee>();
}

string companyName = employee.Company.Name;


Because of the DataLoadOptions I can now use the company properties to print the company name outside the DataContext.

Enjoy.

About the Author

About the Author: Pieter is Technical Marketing Manager for Sitecore Netherlands and owner of Gaatverweg.nl. He has more than ten years experience with software developing in multiple programming languages and with different Content Management Systems. Before joining Sitecore Pieter was a lead developer for multiple Sitecore and .Net projects, he joined Sitecore in 2011 as an Solution Architect in The Netherlands, after two years as an Solution Architect he joined the Technical Marketing department. In the role as Techinical Marketing Manager he is responsible for the Global MVP program and the Sitecore technical branding strategy. You can follow Pieter on twitter: @pieterbrink123 or Google+ .

Subscribe

If you enjoyed this article, subscribe now to receive more just like it.

Post a Comment

Your email address will not be published. Required fields are marked *

Top