Search code examples
asp.netnhibernatenhibernate-criteria

Hibernate, Nhibernate Eager Loading Not working (ignored)


All,

Using nhibernate 5.x, asp.net 4.6.1

I have the following association:

Project Address => Project => Region

I want to query project address and eagerly load project and project region (and also country which is on the project), ... the project is eagerly loaded but the project region is not! When I inspect in the debugger the Region on the project is a proxy type. I tried various queries without success:

 var address = session.CreateCriteria<ProjectAddress>()
                .Add(Expression.Eq(Projections.Id(), addressId))
                .SetFetchMode("Project", NHibernate.FetchMode.Join)
                .SetFetchMode("Project.Region", NHibernate.FetchMode.Join)
                .SetFetchMode("Project.Country", NHibernate.FetchMode.Join)
                .UniqueResult<ProjectAddress>();

and

var address = session.Session.Query<ProjectAddress>()
                .Where(x => x.Id == addressId)
                .Fetch(x => x.Project)
                .ThenFetch(p => p.Region)
                .ThenFetch(p => p.Country)
                .Single();

I've done this in other queries and it works, why its not working in this case is beyond me. There's nothing special about the mapping here (Project=>Region). My mapping:

[ManyToOne(Column = "region_id",
               ClassType = typeof(Region),
                NotNull = false)]
    public virtual Region Region
    {
        get { return _region; }
        set { _region = value; }
    }

Solution

  • OK, I figured out the problem. The reason why Project.Region, Project.Country were proxies is because prior to loading the project address I have loaded a Project into the session somewhere else (without eager loading Region/Country). So, after that I load the project address and hibernate doesn't fetch the project (hence ignoring my fetch strategy) again but uses the cached Project in the session. This can be verified by calling Session.EvictAll() before loading my project address.

    Is there a way in hibernate to explicitly tell to execute fully query (without using Evict())?