I am using NHibernate and I want to control fetching related entities manually.
Here is my sample entity
public class Post
{
public virtual long Id { get; set; }
public virtual string Title { get; set; }
public virtual User User { get; set; }
public virtual IList<Like> Likes { get; set; }
public virtual IList<Tag> Tags { get; set; }
}
The behvaiour I expect is as follows:
session.Query<Post>().ToList();
After this kind of query I want Post
entities to have:
- Primitive properties are set
User
property is not null but only have Id property set.Likes
andTags
are null or empty collection
-
session.Query<Post>()
.Fetch(p => p.User)
.Fetch(p => p.Tags)
.ToList();
And after this kind of query I want Post
entities to have:
- Primitive properties are set
User
property is not null and properties are set.Tags
is not null and all items have all properties setLikes
is null or empty collection
Basically what I want from NHibernate is, not to fetch any related entities unless I ask for it to fetch and not cause an NHibernate specific exception (LazyInitialization etc.) when I try to access not fetched properties. The behaviour I expect is not lazy nor eager.
Before "what have you tried" comments, I tried almost all combinations with LazyLoad()
, Not
, Fetch
etc. in Fluent NHibernate mapping configuration along with both statless and stateful sessions.