views:

15

answers:

1

We have an Enrollment object that has a Student object and the Student object has many Enrollment objects. If I leave off the Cascade.SaveUpdate() from the Enrollment's Student reference, updates to the Student table do not execute, but updates to the Enrollment object succeed. But if I add the Cascade.SaveUpdate() on the Enrollment's Student reference, the updates to the Student table work fine, but updates to the Enrollment table fail. No exceptions are thrown, the updates just don't succeed.

There must be some way to be able to save objects on both sides of the relationship, but what am I missing?

Here's the code snips, let me know if you need more:
EnrollmentMap:

    References(x => x.Student)
                .Column("student_id");// without the cascade on the next line, this fails to update changes to Student
                //.Cascade.SaveUpdate();// when uncommented this updates changes to Student but blocks updates to Enrollment

StudentMap:

    HasMany(x => x.Enrollments)
                .KeyColumn("student_id")
                .Inverse()
                .Cascade.SaveUpdate();

Database call:

public Application GetApplication(long applicationId)
        {
            using (var session = sessionFactory.OpenSession())
            {
                var query = session.Linq();
                query.Expand(x => x.Enrollment);
                query.Expand(x => x.Enrollment.Student);
                var result = from entity in query
                             where entity.ApplicationId == applicationId
                             select entity;
                return result.Count() > 0 ? result.First() : null;
            }
        }

Database save:

using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    try
                    {
                        session.SaveOrUpdate(entity);
                        transaction.Commit();
                    }
                    catch(Exception ex)
                    {
                        transaction.Rollback();
                        throw;
                    }
                }
            }
A: 

You should try and load your entity in the same session as you update it. I think that is your problem.

If you really can't do this, then it is possible to 'merge' the entity in to your session (google 'NHibernate merge').

cbp
Thanks for pointing me in the right direction. I changed the SaveOrUpdate to a SaveOrUpdateCopy which calls merge internally and I was able to add the Cascade.SaveUpdate() to the Enrollment entity's Student reference.
RobertC