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

查看:16
本文介绍了在 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,您可以更改 DataloadOptions(C# 中的代码示例):

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() 仅支持 Linq to Entities)

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

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

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