Ehsan
Ehsan

Reputation: 3491

How load a list of object in a Entity by Nhibernate Lazy Loading

I have a project by NHibernate implementation and using Lazy Loading. I have two class in this project : Person and Family. Relation between Those two is aggregation, is mean a Person has a list of Person. Maping is :

  <class name="Person" table="Person_Person" >

    <id name="Id" type="Int64" unsaved-value="0">
      <generator class="native" />
    </id>

    <bag name="Families" inverse="true" table="Person_Family" cascade="delete" >
      <key column="Person_id_fk"/>
      <one-to-many class="Domain.Entities.Family,RCISP.Domain.Entities"/>
    </bag>

  </class>

In this project, I Get a person by ID then add a family to families field in Person and save Person.

Person person = SessionInstance.Get<Person>(id);
Family family = new Family();
family.Name = "Ehsan";
person.Families.Add(family);
SessionInstance.Save(person);

Person saved in database, but family does not apply, Because lazy loading is active. But if before add a family, Execute count on families, my problem is resolved.

int i = person.Families.Count; //Provisional For call in lazy loading
person.Families.Add(family);
SessionInstance.Save(person);

How can i add a family to person without directly load families of person?

Upvotes: 0

Views: 511

Answers (1)

Cole W
Cole W

Reputation: 15303

You'll need to change your cascade style on your Families collection to all-delete-orphan or all

<bag name="Families" inverse="true" table="Person_Family" cascade="all-delete-orphan" >
      <key column="Person_id_fk"/>
      <one-to-many class="Domain.Entities.Family,RCISP.Domain.Entities"/>
</bag>

Upvotes: 1

Related Questions