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

by Pieter Brinkman 15. January 2009 06:04

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.

 

Tags: , ,

ASP.Net | Linq | MSSQL

Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen

About Me

My name is Pieter Brinkman I am Solution Architect for Sitecore in The Netherlands. My interests are mainly ASP.NET, MSSQL and Content Management Systems.

Calendar

<<  February 2012  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
2728291234
567891011

View posts in large calendar

RecentComments

Comment RSS

Most comments