[英]When are records from related tables loaded with LINQ2SQL
假设我有两个表:
并假设我有一个数据库上下文:
var reports = db.Reports();
如何确保每个报告的所有评论都已加载?
此时,我想与数据库断开连接,但仍然可以访问注释。 (例如:)
reports[0].Comments[0].Subject
我假设报告和评论之间存在1-M FK关系(1个报告可以有很多评论)?
一种选择是使用DataLoadOptions.LoadWith方法-类似于以下内容:
var reports = db.Reports();
DataLoadOptions dlo = new DataLoadOptions();
dlo.LoadWith<Reports>(r => r.Comments); // Ask for Comments along with reports
reports.LoadOptions = dlo;
现在,每次您选择有关该数据上下文的报告时,注释都将随同它一起从数据库中获取。
请注意,注释中的所有字段都将被选中-无法使用此方法选择字段的子集。
另一个选项是具体要在Linq查询中选择的内容,例如
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
};
要了解何时运行查询和关闭数据库连接,您将需要了解:
乔恩·斯基克斯(Jon Skeets)的“ C#深入”对这些内容进行了很好的概述,而且我也听说过有关“ Linq in Action”的很好的事情-另外,还有很多关于这些概念的博客文章,这些主题比我能做的要公正得多。在这里; o)
请记住,如果您使用LoadOptions定义多跳路径(报表,注释,另一个实体),则会通过效率很低的代码加载第三跳和更多跳(如果与1:n关系相关):它们将执行每个家长一个查询。 对于报告注释,没关系,将在2个查询中获取它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.