0
我們有一個Enrollment對象,它有一個Student對象,而Student對象有很多Enrollment對象。如果我從註冊的學生引用中離開Cascade.SaveUpdate(),則不會執行對Student表的更新,但對Enrollment對象的更新會成功。但是,如果我在註冊的學生引用上添加Cascade.SaveUpdate(),則對Student表的更新工作正常,但對註冊表的更新失敗。沒有例外情況發生,更新只是不成功。流利的NHibernate一對多Cascade.SaveUpdate()阻止更新到實體
必須有一些方法可以保存關係兩邊的對象,但是我錯過了什麼?
下面的代碼剪,讓我知道如果你需要更多:
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();
數據庫調用:
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; } }
數據庫保存:
using (var session = sessionFactory.OpenSession()) { using (var transaction = session.BeginTransaction()) { try { session.SaveOrUpdate(entity); transaction.Commit(); } catch(Exception ex) { transaction.Rollback(); throw; } } }
謝謝你指點我在正確的方向。我將SaveOrUpdate更改爲SaveOrUpdateCopy,它在內部調用合併,並且可以將Cascade.SaveUpdate()添加到Enrollment實體的Student引用。 – RobertC 2010-07-16 19:13:23