Linq to NHibernate 生成到同一个表的多个联接

发布于 2024-11-01 10:12:20 字数 744 浏览 2 评论 0原文

当我在 select 和 where 子句中引用同一个表时,linq to Nhibernate 会生成两个连接,一个用于 select,一个用于 where。 ie

from child in Session.Query<Child>()
where child.Parent.Name == "Bob" 
select new Info 
{ 
   ParentAge = child.Parent.Age, 
   ChildName = child.Name
};

生成如下 SQL:

Select this_.Name,
       parent1.Age
From Child this_
     left join Parent parent1 on child.ParentId = parent1.Id,
Parent parent2

Where child.ParentId = parent2.Id and parent2.Name = 'Bob'

我本以为我应该得到更像这样的 SQL:

Select this_.Name,
       parent1.Age
From Child this_
         inner join Parent parent1 on child.ParentId = parent1.Id
Where parent1.Name = 'Bob'

有没有办法构建查询来得到这个? 有关系吗?

When I have a reference to the same table in my select as in my where clause, linq to Nhibernate generates two joins, one for the select and one for the where. i.e.

from child in Session.Query<Child>()
where child.Parent.Name == "Bob" 
select new Info 
{ 
   ParentAge = child.Parent.Age, 
   ChildName = child.Name
};

Generates SQL like:

Select this_.Name,
       parent1.Age
From Child this_
     left join Parent parent1 on child.ParentId = parent1.Id,
Parent parent2

Where child.ParentId = parent2.Id and parent2.Name = 'Bob'

I would have thought I should get SQL more like:

Select this_.Name,
       parent1.Age
From Child this_
         inner join Parent parent1 on child.ParentId = parent1.Id
Where parent1.Name = 'Bob'

Is there a way to structure the query to get this?
Does it matter?

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

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

发布评论

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

评论(2

这个俗人 2024-11-08 10:12:20

您可以使用透明标识符来阻止 NHibernate 执行此操作,以便您的查询如下所示:

from child in Session.Query<Child>()
let p = child.Parent
where p.Name == "Bob" 
select new Info { 
    ParentAge = p.Age, 
    ChildName = child.Name
};

You can prevent NHibernate from doing this by using a transparent identifier, so that your query looks like this:

from child in Session.Query<Child>()
let p = child.Parent
where p.Name == "Bob" 
select new Info { 
    ParentAge = p.Age, 
    ChildName = child.Name
};
皓月长歌 2024-11-08 10:12:20

您是否尝试过比较 SSMS 中每个查询的执行计划?如果在 SQL Server 中消除了重复的联接,那么就没有关系了。我发现在某些情况下,我认为生成的查询效率非常低,但经过优化后,它最终与查询完全相同,看起来要好得多。

Have you tried comparing the query execution plan for each in SSMS? If the duplicated join is eliminated in SQL Server, then it doesn't matter. I've found that to be the case in a few instances where I thought the generated query was going to be very inefficient, but after optimization it ends up exactly the same as a query that looks much better.

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