有人可以用下面的例子解释 Linq 中的查询重塑吗?

发布于 2024-09-15 13:57:37 字数 661 浏览 2 评论 0原文

我正在阅读这篇有关构建的 ASP.NET 文章您的第一个 asp.net mvc 2 网站,我遇到了一个在查询中使用 Include 方法的 Linq 查询。我使用过一些 linq,但我从未使用过 Include 方法,并且想要更好的解释。它会转化为 linq 中的连接吗?有什么好处?以下是文章中的查询:

var genreModel = storeDB.Genres
                        .Include("Albums")
                        .Single(g => g.Name == genre);

文章指出:

实体框架功能允许我们指定我们想要加载的其他相关实体,称为查询结果整形。我们想要加载匹配流派的专辑,因此我们将从 Genres.Include("Albums") 进行查询,以表明我们也需要相关专辑。这更有效,因为它将在单个数据库请求中检索我们的流派和专辑数据。

我有点理解作者上面所说的内容,但觉得我需要更好的示例或解释,特别是因为我以前从未使用过 Include 方法。

I am reading this asp.net article on building your first asp.net mvc 2 website and I came across a Linq query that uses the Include method in the query. I have used some linq, but I have never used the Include method and would like a better explanation. Does it translate to an join in linq? What is the benefit? Here is the query from the article:

var genreModel = storeDB.Genres
                        .Include("Albums")
                        .Single(g => g.Name == genre);

The article states that:

Entity Framework feature that allows us to specify other related entities we want loaded as well, called Query Result Shaping. We want to load the Albums for the matching Genre, so we'll query from Genres.Include("Albums") to indicate that we want related albums as well. This is more efficient, since it will retrieve both our Genre and Album data in a single database request.

I sort of understand what the author is saying above, but feel I would need a better example or explanation, especially since I have never used the Include method before.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

水中月 2024-09-22 13:57:37

如果检查生成的 sql,您会注意到专辑表已加入。它应该看起来像这样:

SELECT [t0].*, [t1].*
FROM Genres [t0]
LEFT JOIN Albums [t1] ON [t0].GenreId = [t1].GenreId
WHERE [t0].Name == @p0

当结果返回到客户端时,ObjectContext 会将行列形状转换为流派和专辑的实例。这些实例将按层次结构相关 - 单一流派及其所有专辑。

假设这个流派有 5 张专辑。该查询将返回 5 行。对象上下文将创建一个 Genre 实例(5 行中的每一行都具有相同的 Genre 主键值)。

If you inspect the generated sql, you'll notice that the Albums table is joined in. It should look something like:

SELECT [t0].*, [t1].*
FROM Genres [t0]
LEFT JOIN Albums [t1] ON [t0].GenreId = [t1].GenreId
WHERE [t0].Name == @p0

When the results get back to the client side, the ObjectContext will turn the row-column shape into instances of Genres and Albums. These instances will be related hierarchically - the single Genre with all of its Albums.

Suppose this genre has 5 albums. The query will return 5 rows. The object context will create one instance of Genre (each of the 5 rows has the same Genre primary key value).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文