Error in Cascade : a different object with the same identifier value was already associated with the session

4.1k views Asked by At

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 Family. Mapping 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="all-delete-orphan" >
      <key column="Person_id_fk"/>
      <one-to-many class="Domain.Entities.Family,Domain.Entities"/>
    </bag>

  </class>

In this project, I Get a person by ID then update a family of families person.

Person person = SessionInstance.Get<Person>(id);
foreach (Family fam in person.Families)
    if (fam.Name == "Jaun")
        {
        fam.Code = 100;
        SessionInstance.Update(fam);
        }

The family not updated, Because throw a exception by this message : `a different object with the same identifier value was already associated with the session: 193, of entity: Domain.Entities.Family

How can i update a family of person?

2

There are 2 answers

0
Cole W On BEST ANSWER

In your case here you do not need to call Update. You just need to flush the session. In your case I would do something like this:

using (ITransaction transaction = SessionInstance.BeginTransaction())
{
    foreach (Family fam in person.Families)
    {
        if (fam.Name == "Jaun")
        {
            fam.Code = 100;
        }
    }

    transaction.Commit();
}

Or you can do something like this:

foreach (Family fam in person.Families)
{
    if (fam.Name == "Jaun")
    {
        fam.Code = 100;
    }
}

SessionInstance.Flush();

ISession.Update() is meant for updating detached objects. In your case the object is not detached. You should read the following 2 sections in the NHibernate documenation to have a better understanding of this:

http://www.nhforge.org/doc/nh/en/index.html#manipulatingdata-updating-insession
http://www.nhforge.org/doc/nh/en/index.html#manipulatingdata-updating-detached

4
Zohaib On

try to update person object instead of family object.

Person person = SessionInstance.Get<Person>(id);
foreach (Family fam in person.Families)
    if (fam.Name == "Jaun")
        {
        fam.Code = 100;
        }
SessionInstance.Update(person);