在linq to sql中,如何在初始查询中包含子实体? [英] In linq to sql how do I include the child entity with initial query?

查看:63
本文介绍了在linq to sql中,如何在初始查询中包含子实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够在linq to sql查询中将子实体和主要实体包括在内.

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

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

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

推荐答案

对于LINQ to SQL,您可以更改

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;

((仅对Linq to Entities支持Include())

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

这篇关于在linq to sql中,如何在初始查询中包含子实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆