在linq to sql中,如何在初始查询中包含子实体?

Ric*_*chC 6 linq-to-sql

我希望能够在我的linq to sql查询中包含一个带有主实体的子实体.

Public Function GetEmployees() As IEnumerable(Of Employee)
    Dim dc As New MyDataContext()
    Return From e In dc.Employee
End Function
Run Code Online (Sandbox Code Playgroud)

在我的ASPX页面中,我希望显示每个员工的部门,而不必在每次需要每个员工的部门实体的部门名称时返回并查询数据库.

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

如果我将其更改为包含部门,我会收到错误消息:

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]'.
Run Code Online (Sandbox Code Playgroud)

Bro*_*ass 14

对于LINQ to SQL,您可以更改DataloadOptions(C#中的代码示例):

var dlo = new DataLoadOptions();
dlo.LoadWith<Employee>(p => p.department);
dc.LoadOptions = dlo;
Run Code Online (Sandbox Code Playgroud)

(Include()仅支持Linq to Entities)