Reputation: 8637
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;
}
}
Upvotes: 2
Views: 4606
Reputation: 1606
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>();
Upvotes: 3