2
votes

Apologies for such a noob question.

I have two entities: Parent and Child, modeled thusly:

public class Parent()
{
 public virtual int ID{ get; protected set; },
 public virtual IList<child> Children {get;set;}
}

public class Child()
{
 public virtual int ID{ get; protected set; },
 public virtual Parent Parent {get;set;}
}

With these mappings:

public class ParentMap : ClassMap<Parent>
{
 public ParentMap()
 {
 Id(x => x.Id).GeneratedBy.Identity(); 
 HasMany(x=>x.Children)
 .Cascade
 .AllDeleteOrphan()
 .Inverse();
 }
}

public class ChildMap : ClassMap<Child>
{
 public ChildMap()
 {
  Id(x => x.Id).GeneratedBy.Identity(); 
  References(x=>x.Parent)
  .Cascade
  .SaveUpdate();
 }
}

I have left lazy loading on, as a parent can have many children and I don't want to always load the children.

I have tried the following methods:

var query1 = Session.QueryOver<Parent>()
.Where(x => x.Id == parent.Id)
.Fetch(t=>t.Children).Eager().List<Parent>();

var query2 = Session.CreateCriteria<Parent>("d")
            .Add(Restrictions.Eq("Id", parent.Id))
            .SetFetchMode("d.Children", FetchMode.Eager)
            .List<Parent>();

var query3 = Session.CreateCriteria(typeof (Parent))
            .Add(Restrictions.Eq("Id", parent.Id))
            .SetFetchMode("Children", FetchMode.Eager)
            .List<Parent>();

I've simplified the objects, of course, but I've also tried these in their own console app, just to test. The problem is: in none of those queries do I actually get the children.

Looking at SQL Profiler, I cannot see any join being generated by nhibernate. I know I can just go the other way and get the parent from the children, but I'd rather not do that.

I think I am missing something fundamental in my understanding of Nhibernate.

Thanks for any help

1
The ID properties don't need to be virtual. Also, you are not explicitly adding ParentID property in Child class. Oh, and you have () on the Children property of the Parent class.DavidG
Do you mean that I need to explicitly put the parent ID as the mapping column? Because this join actually works as the child has a reference to the parent. edit: I also verified that the child is actually making it to SQL. I'm just somehow not able to retrieve it.Macario Tala
Not sure you need to, hence this is a comment rather than an answer. But I like to be explicit in these things in my code :-)DavidG
ah. quite. I'll try that.Macario Tala

1 Answers

2
votes

Resolved this, and should really have included more details in the first code example.

I tried to retrieve the child objects of the parent after saving the parent(with cascade) in the same session.

Closing the session and trying any one of the above queries returned the child(ren).