何时使用 LINQ2SQL 加载相关表中的记录
假设我有两个表:
- 报告
- 评论
假设我有一个数据库上下文:
var reports = db.Reports();
如何确保每个报告的所有评论都已加载?
此时我想断开与数据库的连接但仍然 可以访问评论。 (例如:)
reports[0].Comments[0].Subject
Let's say I have two tables:
- Report
- Comment
And assuming I have a database context:
var reports = db.Reports();
How can I make sure all Comments for each report are loaded as well?
At this point I want to disconnect from the database but still
have access to the comments. (For example:)
reports[0].Comments[0].Subject
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我假设报告和评论之间存在 1-M FK 关系(1 个报告可以有许多评论)?
一种选择是使用 DataLoadOptions.LoadWith< /a> 方法 - 类似于以下内容:
现在,每次您选择该数据上下文的报告时,都会从数据库中获取注释。
请注意,注释中的所有字段都将被选择 - 无法使用此方法来选择字段的子集。
另一种选择是具体说明您要在 Linq 查询中选择的内容,例如
要了解查询何时运行以及数据库连接何时关闭,您需要了解:
Jon Skeets“C# 深入”给出了这些的一个很好的概述,并且我'我们还听说过有关“Linq in Action”的好消息 - 另外还有很多关于这些概念的博客文章,这些文章比我在这里能做到的更公正地阐述主题;o)
I'm assuming that there is an 1-M FK relationship between reports and comments (1 Report can have many Comments)?
One option is to use the DataLoadOptions.LoadWith method - something like the following:
Now, every time you select a report on that data context, the comments will be fetched from the db along with it.
Just beware that ALL fields from comments will be selected - there is no way using this method to select a subset of fields.
Another option is to be specific about what you want to select in the Linq query, e.g.
To understand when the query gets run and the database connection closed, you will need to understand:
Jon Skeets "C# in depth" gives a great overview of these, and i've also heard very good things about "Linq in Action" - plus there are plenty of blog posts about these concepts which do the subjects more justice than I can do here ;o)
请记住,如果您使用 LoadOptions 定义多跳路径(报告、注释、另一个实体),则通过代码加载第三跳和更多跳(如果与 1:n 关系相关),效率非常低:它们将执行每个家长一次查询。 对于报告评论,没关系,它们将在 2 个查询中获取。
Keep in mind that if you use LoadOptions to define a multi-hop path (Reports, comments, anotherentity), the 3rd and further hops are loaded (if related over 1:n relationships) by code which is very inefficient: they'll execute one query per parent. For reports-comments, it's ok, they'll be fetched in 2 queries.