3

I am using nhibernate and I wrote a linq query and it is not returning what I expect.

public ParentA()
{
    public virtual Id {get; set;}
    public virtual Name {get; set;}
    public virtual IList<ChildA> ChidrenA {get; set;}

   public ParentA()
   {
       ChidrenA = new List<ChildA>();      
   }
}

public ChildA()
{
    public virtual Id {get; set;}
    public virtual Name {get; set;}
    public virtual IList<ChildB> ChidrenB {get; set;}
    public virtual ParentA ParenteA {get; set;}
   public ChildA()
   {
       ChidrenB = new List<ChildB>();      
   }
}

public ChildB()
{
    public virtual Id {get; set;}
    public virtual Name {get; set;}
    public virtual ChildA {get; set;}
}

The above code is my domains. The fluent nhibernate would be very basic and nothing special going on so I have not included it.

The query I have is

base.unitOfWork.Session.Query<ParentA>()
  .Where(x => x.Id == parentAId)
  .FetchMany(x => x.ChildrenA)
  .ThenFetchMany(x => x.ChildrenB)
  .FirstOrDefault();

What I expected to happen

It will find 1 or 0 parent records. If it does find that one record it will eager load all ChildrenA and then all ChildrenB.

What is happening

It finds 1 or 0 parent records. It then only takes 1 or 0 record for ChildrenA and ChildrenB.

Why is only taking the first found record for ChildrenA and ChildrenB?

If I change FirstToDefault() to .toList() I get everything I expect but I find it pointless as there should only be one record with that parent record.

Richard Schneider
  • 34,944
  • 9
  • 57
  • 73
chobo2
  • 83,322
  • 195
  • 530
  • 832

2 Answers2

3

Actually you dont need the Where ...First or default takes lambda expression

  .FirstOrDefault(x => x.Id == parentAId).

So instead of Where , use the the above statement

Dan Hunex
  • 5,172
  • 2
  • 27
  • 38
2

Try moving .FirstOrDefault to directly after the .Where clause:

.Where(x => x.Id == parentAId).FirstOrDefault()...
mellamokb
  • 56,094
  • 12
  • 110
  • 136
  • 5
    Then you could also replace `.Where()` with `FirstOrDefault()` as it basically does the same thing. FirstOrDefault( x => x.Id == parentAId )... – LazyTarget Feb 05 '13 at 18:03
  • @LazyTarget: Very good point :) – mellamokb Feb 05 '13 at 18:04
  • Ya that's what I thought and tried to move FirstOrDefault() to after the where but then I lost the fetches. It would not let me use them. – chobo2 Feb 05 '13 at 18:16