双向多对一生成 SELECT N+1
我有两个使用 NHibernate 映射的类:类 Application 引用带有属性 StoreId 的类 Store。应用程序用户有一个身份 ID,而 Store 类有一个分配的 ID,但我认为在这种情况下这并不重要。
ApplicationUser 映射:
<many-to-one name="Store" column="StoreId" class="Store" />
Store 映射:
<many-to-one name="ApplicationUser" column="Id" class="ApplicationUser"
property-ref="Store" insert="false" update="false"
fetch="join" outer-join="true" />
当我加载所有 Store 时,会按预期生成 ApplicationUser 的左外连接,但是在构建对象图时,NHibernate 决定执行额外的 SELECT ... FROM ApplicationUser WHERE StoreId = ?
对于每个不引用 ApplicationUser 的 Store。
这是巨大的杀伤力,完全没有必要,因为它应该已经知道那些 ApplicationUsers 不存在。
有人知道如何阻止 NHibernate 生成这些额外的查询吗?
编辑:
类非常基础,如下所示:
public class Store
{
public virtual int Id { get; set; }
// ...
public virtual ApplicationUser ApplicationUser { get; set; }
}
public class ApplicationUser
{
public virtual int Id { get; set; }
// ...
public virtual Store Store { get; set; }
}
I have two classes mapped with NHibernate: class Application references class Store with a property StoreId. Application user has an identity id while class Store has an assigned id but I don't believe that matters in this case.
ApplicationUser mapping:
<many-to-one name="Store" column="StoreId" class="Store" />
Store mapping:
<many-to-one name="ApplicationUser" column="Id" class="ApplicationUser"
property-ref="Store" insert="false" update="false"
fetch="join" outer-join="true" />
When I load all Stores, a left outer join is generated to ApplicationUser as expected, but then when building the object graph NHibernate decides to do an extra SELECT ... FROM ApplicationUser WHERE StoreId = ?
for every Store that doesn't reference an ApplicationUser.
This is massive overkill and totally unnecessary since it should already know that those ApplicationUsers don't exist.
Anyone knows how to stop NHibernate from generating these extra queries?
EDIT:
Classes are very basic, like this:
public class Store
{
public virtual int Id { get; set; }
// ...
public virtual ApplicationUser ApplicationUser { get; set; }
}
public class ApplicationUser
{
public virtual int Id { get; set; }
// ...
public virtual Store Store { get; set; }
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为这里发生的事情是 nHibernate 正在尝试加载两个集合,因为您已将每个集合指定为“多对一”...我认为除了修改映射之外您无能为力...
所以-> xb 和 b -> xa,我的理解是 nHibernate 会查询这两种关系......对我来说是有道理的。
如果不需要集合,您不能将其包含在查询中并依赖延迟加载。
I think what's happening here is that nHibernate is attempting to load both collections as you've got each specified as 'many to one'... I don't think there's anything you can do short of modifying your mappings...
So a -> xb and b -> xa, my understanding would be that nHibernate would have query both relations... Makes sense to me.
You could not include it in your query and rely on lazy loading if the collections aren't needed.