LINQ To SQL - Performing Inner Join Queries
Its amazing how simple it is to create inner join queries with LINQ.
Assuming you have the AdventureWorks Database installed.
public void GetEmployeeByID(int employeeID)
{
AdventureWorksDataContext aw = new AdventureWorksDataContext();
aw.Log = Console.Out;
var entities = from e in aw.Employees
join ea in aw.EmployeeAddresses on e.EmployeeID equals ea.EmployeeID
join a in aw.Addresses on ea.AddressID equals a.AddressID
join c in aw.Contacts on e.ContactID equals c.ContactID
where e.EmployeeID == employeeID
select new
{
Title = e.Title,
FirstName = c.FirstName,
LastName = c.LastName,
City = a.City,
AddressID = ea.AddressID
};
foreach (var e in entities)
{
Console.WriteLine("Title = {0}, FirstName = {1}, LastName = {2}",
e.Title, e.FirstName, e.LastName);
}
}
The text query and the results:
