VJAI
VJAI

Reputation: 32758

Issue in loading children eagerly

I'm using NHibernate with FluentNH.

Here are the four classes.

FormType

  public class FormType
  {
    public virtual int Id
    { get; set; }

    public virtual string Name
    { get; set; }

    public virtual IList<KeyCompetency> KeyCompetencies 
    { get; set; }
  }

KeyCompetency

  public class KeyCompetency
  {
    public virtual int Id
    { get; set; }

    public virtual string Name
    { get; set; }

    public virtual FormType FormType
    { get; set; }

    public virtual IList<SubCompetency> SubCompetencies 
    { get; set; }
  }

SubCompetency

  public class SubCompetency
  {
    public virtual int Id
    { get; set; }

    public virtual string Name
    { get; set; }    


    public virtual KeyCompetency KeyCompetency
    { get; set; }

    public virtual IList<Ability> Abilities 
    { get; set; }
  }

Ability

  public class Ability
  {
    public virtual int Id
    { get; set; }

    public virtual string Description
    { get; set; }

    public virtual SubCompetency SubCompetency
    { get; set; }
  }

I'm trying to load a formtype based on id.

using (var session = DataContext.OpenSession())
{
    return session.Query<FormType>()
                  .Where(x => x.Id == 1)
                  .FetchMany(x => x.KeyCompetencies)
                  .ThenFetchMany(x => x.SubCompetencies)
                  .ThenFetchMany(x => x.Abilities)
                  .ToList().FirstOrDefault();
}

I'm getting duplicate records for key-competencies, sub-competencies.

Upvotes: 0

Views: 62

Answers (1)

Jamie Ide
Jamie Ide

Reputation: 49261

Map the collections as Set to avoid this problem. See the answer to this question. Also, since you're selecting by identity it's better to use .SingleOrDefault instead of FirstOrDefault.

Upvotes: 2

Related Questions