Map collection as QueryOver<> #204

techniq opened this Issue Jan 23, 2013 · 6 comments


None yet
3 participants

techniq commented Jan 23, 2013

I've grown accustomed in SQLAlchemy (Python) to map a relationship/collection with lazy="dynamic" which maps the property as a Query object instead of a populated list/collection (or Proxy for lazy loaded properties). This mapped property then allows you to further refine the query used to fetch the collection before doing so (apply an order, limit, filter, etc).

For example, in SQLAlchemy I can map a relationship like so:

class Post(Base):

class User(Base):
    posts = relationship(Post, lazy="dynamic")

And then when I retrieve a user, I can apply an order on posts, or only retrieve the last 5, etc.

user = session.query(User).get(1)

# Fetch the last 5 posts by user 1
posts = user.posts.order_by(Post.create_date.desc()).limit(5).all()

I would love to find a way to do this using Fluent NHibernate, mapping the collection as a QueryOver or IQueryable (LINQ) such as:

public virtual QueryOver<Post> Posts {get; set;}
public virtual IQueryable<Post> Posts { get; set; }

and in the mappings do something like:

public class UserMap : ClassMap<User>
    public UserMap()
        HasMany(u => u.Posts).Fetch.Dynamic

Is this currently possible using Fluent NHibernate (or just NHibernate)?


chester89 commented Feb 4, 2013

I don't think that's possible. Any other NH users know about this?

techniq commented Feb 4, 2013

I originally asked this on StackOverflow (, and received this response:

It is possible using NHibernate, however it's not quite out of the box.

You would need to write your own collectionwrapper implementing IQueryable, inject it with your own CollectionFactory and delegate the query generation to the session which loaded the containing object.


chester89 commented Feb 4, 2013

I see. If you provide the NHibernate part of the solution, I'll try to expand the Fluent API to allow this scenario

techniq commented Feb 4, 2013

Sounds good, I'll see what I can do. It will probably be a while for me to get around to this (jumping between a lot of projects lately), but I'll update this issue when I do (or if something updates my StackOverflow question with a full solution).

Did you ever make any progress on this? I have found a need for exactly this behaviour

techniq commented Jul 29, 2014

I didn't and have since moved to NPoco for database access.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment