C# 何时使用LINQ2SQL加载相关表中的记录

C# 何时使用LINQ2SQL加载相关表中的记录,c#,linq-to-sql,database-relations,loadoptions,C#,Linq To Sql,Database Relations,Loadoptions,假设我有两张桌子: 报告 评论 假设我有一个数据库上下文: var reports = db.Reports(); 如何确保每个报告的所有注释都已加载 此时,我想断开与数据库的连接,但仍然 有权访问评论。(例如:) 我假设报告和评论之间存在1-m FK关系(1份报告可以有许多评论) 一种选择是使用该方法-类似于以下内容: var reports = db.Reports(); DataLoadOptions dlo = new DataLoadOptions(); dlo.LoadWith

假设我有两张桌子:

  • 报告
  • 评论
假设我有一个数据库上下文:

var reports = db.Reports();
如何确保每个报告的所有注释都已加载

此时,我想断开与数据库的连接,但仍然 有权访问评论。(例如:)


我假设报告和评论之间存在1-m FK关系(1份报告可以有许多评论)

一种选择是使用该方法-类似于以下内容:

var reports = db.Reports();
DataLoadOptions dlo = new DataLoadOptions();
dlo.LoadWith<Reports>(r => r.Comments);      // Ask for Comments along with reports
reports.LoadOptions = dlo;
要了解何时运行查询并关闭数据库连接,您需要了解:

  • Linq和Linq To Sql的延迟执行模型(基本上,对于Linq To Sql,查询仅在请求结果时运行,例如通过迭代集合或绑定到网格)
  • IQueryable和IEnumerable之间的区别

Jon Skeets的“C#indepth”对这些概念有很好的概述,我也听说过关于“Linq in Action”的很好的东西——此外,还有很多关于这些概念的博客文章,它们比我在这里能做的更公正;o)

请记住,如果使用LoadOptions定义多跳路径(报告、注释和其他实体),则第三个和更多的跳将通过代码加载(如果与1:n关系相关),这是非常低效的:它们将对每个父级执行一个查询。对于报告和评论,没关系,它们将在两个查询中获取

var reports = db.Reports();
DataLoadOptions dlo = new DataLoadOptions();
dlo.LoadWith<Reports>(r => r.Comments);      // Ask for Comments along with reports
reports.LoadOptions = dlo;
var myReportsList = from report in db.Reports
                    select new {  // Using anonymous type, but could use a custom class
                       Report = report,
                       Comment = report.Comment.Detail,   // for example
                       Subject = report.Comment.Subject
                    };