Some things to watch out for when working with NHibernate...
If you update an NHibernate entity without detaching it first from the session, it will be updated automatically.
[Test]
public void UpdatedEntityPropertyWillSaveAutomatically()
{
Customer customer = null;
try
{
customer = _Repository.GetFirst();
customer.FirstName = null; // First Name can not be null, so this will throw an exception
_Repository.Flush(); // flush happens also when the session ends.
}
catch(Exception ex)
{
Assert.That(ex.InnerException is System.Data.SqlClient.SqlException);
_Repository.Clear();
return;
}
Assert.Fail("We should never get here, because flushing the repository will throw the exception above.");
}
If you do not detach your object from its repository, NHibernate will pass you a reference to the same object.
[Test]
public void IfNotDetachedTwoObjectsHaveTheSameReference()
{
Customer c1 = _Repository.GetFirst();
Customer c2 = _Repository.GetById(c1.ID);
c1.LastName += "1";
Assert.AreEqual(c1.LastName, c2.LastName);
}
[Test]
public void IfDetachedAnObjectWillNotHaveTheSameReference()
{
Customer c1 = _Repository.GetFirst();
_Repository.Evict(c1);
Customer c2 = _Repository.GetById(c1.ID);
c1.LastName += "1";
Assert.AreNotEqual(c1.LastName, c2.LastName);
}