2

How to load complete object (that has all asociated objects within) using Fluent NHibernate? In this case the object is named Project and has associated Category and list of Pictures. Mapping file looks like this:

        public ProjectMap()
    {
        Id(x => x.Id);

        Map(x => x.Title).Not.Nullable();
        Map(x => x.Year);
        Map(x => x.Slug).Not.Nullable();
        Map(x => x.Description).CustomSqlType("nvarchar(MAX)").Not.Nullable();
        References(x => x.Category, "CategoryId").Not.Nullable();
        HasMany(x => x.Gallery)
            .Inverse()
            .Cascade.All();
    }

And repository method that should return the complete object:

public Project Read(int id)
    {
        using (var session = NHibernateHelper.OpenSession())
        {
            var project = session.CreateQuery("FROM Project WHERE Id = :Id LEFT JOIN FETCH p.Category LEFT JOIN FETCH p.Gallery")
                .SetParameter("Id", id).UniqueResult<Project>();
            return project;
        }
    }

1 Answer 1

3

I'm assuming you want to lazy load by default, but sometimes you want eager loading when necessary. If you always want to eager load (not recommended), you should do that in the mapping instead with Not.Lazyload and choosing a fetch strategy with .Fetch().

Otherwise, you will have to use one of the query methods in NHibernate to do what you want. You can do this with an HQL query, or Linq query, and probably with a Criteria query.

Here's a LINQ query (this works in 3.2, not sure if it's available before then)

session.Linq<Project>()
    .Fetch(p => p.Category)
    .FetchMany(p => p.Gallery).FirstOrDefault();

Here's an HQL version

session.CreateQuery("SELECT p FROM Project p FETCH JOIN p.Category FETCH JOIN p.Gallery")
    .UniqueResult<Project>();

Here's a Criteria version

session.CreateCriteria<Project>("p")
    .SetFetchMode("p.Category", FetchMode.Join)
    .SetFetchMode("p.Gallery", FetchMode.Join)
    .UniqueResult<Project>();
Sign up to request clarification or add additional context in comments.

1 Comment

I have used the ".CreateQuery("FROM Project WHERE Id = :Id LEFT JOIN FETCH p.Category LEFT JOIN FETCH p.Gallery") .SetParameter("Id", id).UniqueResult<Project>();" but it doesn't work.. I still get the error "Initializing[Model.Entities.Category#1]-Could not initialize proxy - no Session."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.