如何使用LINQ to SQL加载兄弟数据?

目标是使用LINQ to sqlsql Server发出最少的查询,而不使用匿名类型.该方法的返回类型将需要为IList< Child1>.关系如下:
Parent
    Child1          Child2
Grandchild1

父母> Child1是一对多关系

Child1> Grandchild1是一对一的关系(其中n为零到无穷大)

父母> Child2是一对一的关系(其中n为零到无穷大)

我能够加载Parent,Child1和Grandchild1数据,从而对sql Server进行一次查询.

加载选项的此查询加载所有数据,但兄弟数据(Child2)除外:

DataLoadOptions loadOptions = new DataLoadOptions();
loadOptions.LoadWith<Child1>(o => o.GrandChild1List);
loadOptions.LoadWith<Child1>(o => o.Parent);

dataContext.LoadOptions = loadOptions;

IQueryable<Child1> children = from child in dataContext.Child1
                                select child;

我也需要加载兄弟数据.我尝试的一种方法是将查询分成两个LINQ到SQL查询,并将结果集合在一起(不漂亮),但是在访问兄弟数据时,它仍然是懒惰的加载.

添加兄弟加载选项将会向sql Server发出针对每个Grandchild1和Child2记录的查询(这正是我正在尝试避免的):

DataLoadOptions loadOptions = new DataLoadOptions();
loadOptions.LoadWith<Child1>(o => o.GrandChild1List);
loadOptions.LoadWith<Child1>(o => o.Parent);
loadOptions.LoadWith<Parent>(o => o.Child2list);

dataContext.LoadOptions = loadOptions;

IQueryable<Child1> children = from child in dataContext.Child1
                                select child;


exec sp_executesql N'SELECT * FROM [dbo].[Child2] AS [t0]
WHERE [t0].[ForeignKeyToParent] = @p0',N'@p0 int',@p0=1

exec sp_executesql N'SELECT * FROM [dbo].[Child2] AS [t0]
WHERE [t0].[ForeignKeyToParent] = @p0',@p0=2

exec sp_executesql N'SELECT * FROM [dbo].[Child2] AS [t0]
WHERE [t0].[ForeignKeyToParent] = @p0',@p0=3

exec sp_executesql N'SELECT * FROM [dbo].[Child2] AS [t0]
WHERE [t0].[ForeignKeyToParent] = @p0',@p0=4

我也写了LINQ to SQL查询,以加入所有的数据,希望它能够加载数据,但是当访问了Child2或者Grandchild1的LINQ to sql EntitySet时,它会延迟加载数据.

返回IList< Child1>的原因是为了水合生意对象.

我的想法是:

>接近这个问题的方式错了.
>可以选择调用存储过程吗?
>我的组织不应该使用LINQ to sql作为ORM?

任何帮助是极大的赞赏.

谢谢,

斯科特

解决方法

你应该是正确的,你需要添加这个dataContext.DeferredLoadingEnabled = false;除了您已经设置的LoadOptions之外.

相关文章

SELECT a.*,b.dp_name,c.pa_name,fm_name=(CASE WHEN a.fm_n...
if not exists(select name from syscolumns where name=&am...
select a.*,pano=a.pa_no,b.pa_name,f.dp_name,e.fw_state_n...
要在 SQL Server 2019 中设置定时自动重启,可以使用 Window...
您收到的错误消息表明数据库 &#39;EastRiver&#39; 的...
首先我需要查询出需要使用SQL Server Profiler跟踪的数据库标...