In linq to sql how to include a child object with the original query?

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

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

On my ASPX page, I want to display the Department of each employee without having to go back and query the database every time he needs the department name from the department unit for each 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 a department in it, I get an error message:

 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]'. 
+6
source share
1 answer

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

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

( Include() is only supported for Linq for objects)

+14
source

Source: https://habr.com/ru/post/886652/


All Articles