Sco*_*ott 16 linq eager-loading linq-to-sql
目标是使用LINQ to SQL向SQL Server 发出最少的查询,而不使用匿名类型.该方法的返回类型需要是IList <Child1>.关系如下:
Parent
Child1 Child2
Grandchild1
Run Code Online (Sandbox Code Playgroud)
Parent> Child1是一对多关系
Child1> Grandchild1是一对一的关系(其中n为0到无穷大)
Parent> Child2是一对一关系(其中n为0到无穷大)
我能够急切加载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;
Run Code Online (Sandbox Code Playgroud)
我也需要加载兄弟数据.我尝试过的一种方法是将查询拆分为两个LINQ to SQL查询并将结果集合并在一起(不太漂亮),但是在访问兄弟数据时它仍然是延迟加载的.
添加兄弟加载选项将为每个Grandchild1和Child2记录向SQL Server发出查询(这正是我试图避免的):
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',N'@p0 int',@p0=2
exec sp_executesql N'SELECT * FROM [dbo].[Child2] AS [t0]
WHERE [t0].[ForeignKeyToParent] = @p0',N'@p0 int',@p0=3
exec sp_executesql N'SELECT * FROM [dbo].[Child2] AS [t0]
WHERE [t0].[ForeignKeyToParent] = @p0',N'@p0 int',@p0=4
Run Code Online (Sandbox Code Playgroud)
我还编写了LINQ to SQL查询以加入所有数据,希望它能够加载数据,但是当访问Child2或Grandchild1的LINQ to SQL EntitySet时,它会延迟加载数据.
返回IList <Child1>的原因是为了保持业务对象.
我的想法是我要么:
任何帮助是极大的赞赏.
谢谢,
斯科特
| 归档时间: |
|
| 查看次数: |
6252 次 |
| 最近记录: |