6

I would like to be able to include a child entity with the main entity in my linq to sql query.

Public Function GetEmployees() As IEnumerable(Of Employee)
    Dim dc As New MyDataContext()
    Return From e In dc.Employee
End Function

In my ASPX page, I want to display the Department of each employee without it having to go back and query the database each time it needs the department name from the department entity for each an every employee.

<asp:repeater...>
   ...
      <%# Eval("FirstName") %><br />
      <%# Eval("LastName") %><br />
      <%# Eval("Department.Name") %> <--- re-queries db every time on this line?
   ...
</asp:repeater>

if I change it to include the department, I get an error:

Public Function GetEmployees() As IEnumerable(Of Employee)
    Dim dc As New MyDataContext()
    Return From e In dc.Employee Select e, e.department
End Function


Unable to cast object of type 'System.Data.Linq.DataQuery`1[VB$AnonymousType_0`2[MyNameSpace.Employee,System.Data.Linq.EntitySet`1[MyNameSpace.Employee.Department]]]' to type 'System.Collections.Generic.IEnumerable`1[MyNameSpace.Employee]'.
RichC
  • 7,853
  • 19
  • 80
  • 137

1 Answers1

14

For LINQ to SQL you can change the DataloadOptions (code example in C#):

var dlo = new DataLoadOptions();
dlo.LoadWith<Employee>(p => p.department);
dc.LoadOptions = dlo;

( Include() is only supported for Linq to Entities)

BrokenGlass
  • 149,257
  • 27
  • 271
  • 318
  • Excellent - thanks! So, I don't need to add it to my particular query each time. I just specify in the datacontext that when I query for Employee, it should also always include the related Department data, correct? – RichC Apr 25 '11 at 22:08
  • @EdenMachine - yes it's on the data context scope – BrokenGlass Apr 25 '11 at 23:29