Bidirectional many-to-one generates SELECT N+1
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开发者_StackOverflow ApplicationUser { get; set; }
}
public class ApplicationUser
{
public virtual int Id { get; set; }
// ...
public virtual Store Store { get; set; }
}
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.
精彩评论