RichC
RichC

Reputation: 7879

In linq to sql how do I include the child entity with initial query?

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]'.

Upvotes: 6

Views: 6812

Answers (1)

BrokenGlass
BrokenGlass

Reputation: 160852

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)

Upvotes: 14

Related Questions