2
votes

I was just wondering whether when loading an entity which contains a collection e.g. a Post which may contain 0 -> n Comments if you can define how many comments to return.

At the moment I have this:

public IList<Post> GetNPostsWithNCommentsAndCreator(int numOfPosts, int numOfComments)
    {
        var posts = Session.Query<Post>().OrderByDescending(x => x.CreationDateTime)
            .Take(numOfPosts)
            .Fetch(z => z.Comments)
                .Fetch(z => z.Creator).ToList();

        ReleaseCurrentSession();
        return posts;
    }

Is there a way of adding a Skip and Take to Comments to allow a kind of paging functionality on the collection so you don't end up loading lots of things you don't need.

I'm aware of lazy loading but I don't really want to use it, I'm using the MVC pattern and want my object to return from the repositories loaded so I can then cache them. I don't really want my views causing select statements.

Is the only real way around this is to not perform a fetch on comments but to perform a separate Select on Comments to Order By Created Date Time and then Select the top 5 for example and then place the returned result into the Post object?

Any thoughts / links on this would be appreciated.

Thanks,

Jon

1
I would imagine the join required for what you're after is too complex for NHibernate, it'd need to know how to use a TOP on posts and on comments as two seperate sub-selects, and then outer join themChris S

1 Answers

0
votes

A fetch simple does a left-outer join on the associated table so that it can hydrate the collection entities with data. What you are looking to do will require a separate query on the specific entities. From there you can use any number of constructs to limit your result set (skip/take, setmaxresults, etc)