什么是延迟加载?
延迟加载机制是为了避免一些无谓的性能开销而提出来的,所谓延迟加载就是当在真正需要数据的时候,才真正执行数据加载操作。
从下图中可以看出,如果不使用延迟加载,那么在取出Department时,会顺带的把用户和订单全部取出来,
对于性能肯定有损耗。
Linq 中对于不需要马上进行加载的数据,提供了延迟加载的功能选项,可让我们根据具体的需要进行选择
DataLoadOptions 类提供了上述的功能
延迟加载:AssociateWith方法
立即加载:LoadWith方法
见以下表结构
- DataLoadOptions ds = new DataLoadOptions();
- ds.AssociateWith<Subject>(Subject=> Subject.Books.Where(p => p.Isbn == "0-222-77777-2"));
- theDataContext.LoadOptions = ds;
- var query = from subjectin theDataContext.GetTable<Subject>()
- where subject.SubjectID == "c603e018-7e60-4cf2-b147-fb13e9be3d72"
- select subject;
可以从调试信息中看出
SQL语句只有Subject表的查询信息
看以下例子,是立即加载的
- DataLoadOptions ds = new DataLoadOptions();
- ds.LoadWith<Subject>(Subject=> Subject.Books.Where(p => p.Isbn== "0-222-77777-2"));
- theDataContext.LoadOptions = ds;
- var query = from subjectin theDataContext.GetTable<Subject>()
- where subject.SubjectID == "c603e018-7e60-4cf2-b147-fb13e9be3d72"
- select subject;
从调试信息中获取的SQL语句
- SELECT [t0].[ID] AS [SubjectID], [t0].[Description], [t0].[Name], [t1].[ID], [t1].[Isbn], [t1].[Notes],
- [t1].[PageCount], [t1].[Price], [t1].[PubDate] AS [PublicationDate], [t1].[Summary],
- [t1].[Title], [t1].[Subject] AS [SubjectID2], [t1].[Publisher] AS [PublisherID],
- (
- SELECT COUNT(*)
- FROM [Book] AS [t2]
- WHERE ([t2].[Isbn] = '0-222-77777-2') AND ([t2].[Subject] = [t0].[ID])
- ) AS [value]
- FROM [Subject] AS [t0]
- LEFT OUTER JOIN [Book] AS [t1] ON ([t1].[Isbn] = '0-222-77777-2') AND ([t1].[Subject] = [t0].[ID])
- WHERE [t0].[ID] = 'c603e018-7e60-4cf2-b147-fb13e9be3d72'
- ORDER BY [t0].[ID], [t1].[ID]
这个时候是加载了两个表,Subject 和 Book 表
从调试信息的,Result View中可以看到,其实不管是使用立即加载还是延迟加载,其实Books信息已经被加入了
Book包含了两个,至于是为什么,我是有点奇怪? 感觉就是结果集预览(Result View),因为从生成的SQL语句中可以看出
,运用延迟加载的只会生成Subject表的SQL语句,不会涉及到Book表