Search code examples
fluent-nhibernatelazy-loadingfluent-nhibernate-mapping

Fluent NHibernate do not load linked collection


I've got two simple entities:

public class Post {
    public virtual int Id {get;set;}
    public virtual string Title {get;set;}
    public virtual IList<Comment> {get;set;}
}

and

public class Comment {
    public virtual int Id {get;set;}
    public virtual string Text {get;set;}
    public virtual Post Post {get;set;}
}

Corresponding mappings looks like:

HasMany(x => x.Comment).LazyLoad();
References(x => x.Post).Not.LazyLoad();

My goal is to load Comments in Posts only if I want it and don't load Comments otherwise. something like that:

var posts = session.QueryOver<Post>().ToList() // load posts without comments
var posts = session.QueryOver<Post>().FetchMany(x => x.Comments).ToList(); // load posts with comments

I'm using FluentNHibernate 2.0.1 and NHibernate 4 with Postgres 9.2


Solution

  • the lazy load convention works mostly on list's only, I have tried my fair share of troubles when I tried to use it on non-collection child elements.

    So yes, you can use .Conventions.Add(DefaultLazy.Always()) but that should be preferred for collections only