如何使用LINQ to SQL加载兄弟数据?
目标是使用LINQ to SQL向SQL 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>的原因是为了水合生意对象. 我的想法是: >接近这个问题的方式错了. 任何帮助是极大的赞赏. 谢谢, 斯科特 解决方法你应该是正确的,你需要添加这个dataContext.DeferredLoadingEnabled = false;除了您已经设置的LoadOptions之外.(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |