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

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(e => e.Company);
   db.LoadOptions = dlo;

   employee = from item in db.Employees
                      select item).First();

string companyName = employee.Company.Name;

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


Leave a Reply

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