Book Image

Learning NHibernate 4

Book Image

Learning NHibernate 4

Overview of this book

Table of Contents (18 chapters)
Learning NHibernate 4
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Transitive persistence using cascade styles


NHibernate implements transitive persistence wherein updates made to a persistent entity are automatically synchronized to database on commit of the transaction. Let's look at a very simple example of how this works. In the following unit test, we save a transient employee instance, thus making it persistent. We then load the persistent instance from database inside a new transaction, update the FirstName and LastName property, and commit the transaction. Lastly, we clear the session and load the same entity instance from database and confirm that FirstName and LastName is updated correctly.

[Test]
public void UpdateEmployee()
{
  object id = 0;
  using (var tx = Session.BeginTransaction())
  {
    id = Session.Save(new Employee
    {
      Firstname = "John",
      Lastname = "Smith"
    });

    tx.Commit();
  }

  Session.Clear();

  using (var tx = Session.BeginTransaction())
  {
    var emp = Session.Get<Employee>(id);

    emp.Firstname...