Question

I have this schema:

enter image description here

I have already done ManyToMany mapping between Post and Tag. What I'm trying to achieve is get the list of Posts and for each Post its child collection of Tags. So it can be displayed like this:

enter image description here

What I have done so far is this:

IList<Post> results = base._session.CreateCriteria(typeof(Post))
    .SetFetchMode("User", FetchMode.Eager)
    .SetFetchMode("Votes", FetchMode.Eager)
    .AddOrder(Order.Desc("_dateCreated"))
    .ToList();

But for every Post it does 1 extra SQL to fetch Votes. Is there a way to fetch it in one go?

Was it helpful?

Solution

The solution in this case could/should be the batch fetching. Here: 19.1.5. Using batch fetching you can find more details.

You have to mark your collections and/or entities with an attribute batch-szie="25".

xml:

<bag name="Tags" ... batch-size="25">
...

fluent:

HasManyToMany(x => x.Tags)
  ...
  .BatchSize(25)

That will still execute few SQL Select statements, not only one, but the flexibility you gain would be significant.

Here I've tried to explain why the batch fetching is the right way to go: NHibernate QueryOver with Fetch resulting multiple sql queries and db hits

At the end, we can use simple queries (not explicit fetching), because batch-size will reduce the amount of SQL Statements issued to get all needed lazy loads...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top