I have a Project and a Person (somewhat simplified):
public class Project
{
public virtual Person CreatedBy { get; set; }
}
public class Person
{
public virtual string Username { get; set; }
}
I’m getting a Project with NH Linq:
var projects = from p in session.Query<Project>()
select p;
var project = projects.First();
and sometimes with Fetch()
var project = projects.Fetch(p => p.CreatedBy).First();
Now, how can I verify in a unit test that project.CreatedBy is not or is eagerly loaded (and the reverse), depending on if Fetch() was used? In my understanding, using Fetch() should eager load the Person and if I don’t use Fetch() it should lazy load the Person.
I’ve tried
Assert.IsTrue(NHibernateUtil.IsInitialized(project.CreatedBy));
And
NHibernateUtil.IsPropertyInitialized(project, "CreatedBy")
But they both return true whether I use Fetch() or not. IsInitialized() works fine with collections (one-to-many), for instance Person.Projects, but not with many-to-one…
The CreatedBy property should be lazy loaded but sometimes I want it to be eagerly loaded and I want unit tests confirming that it’s working as intended.
The mapping for the CreatedBy property is
<many-to-one name="CreatedBy" class="Person" fetch="select">
<column name="PERSON_ID" precision="10" scale="0" not-null="true" />
</many-to-one>
I verified the mapping like this:
var to1 = NHibernateConfiguration.GetClassMapping(typeof(Project))
.ReferenceablePropertyIterator.FirstOrDefault(p => p.Name == "CreatedBy")
.Value as NHibernate.Mapping.ToOne;
Assert.IsTrue(to1.IsLazy);
Assert.IsFalse(to1.UnwrapProxy);
Which passes.
Any ideas?
If
NHibernateUtil.IsInitialized(project.CreatedBy)returns true, it’s because it is initialized.If the Person has already been loaded in the session, it will be initialized regardless of whether you fetch CreatedBy eagerly or not, thanks to the Identity Map.