The following unit test fails, I make changes to an object that I’ve retrieved and then in the same session I make a query which appears to take into account the uncommited changes I’ve made to the object.
How can I get NHibernate to ignore any uncommited changes and only query the database?
[Test]
public void Test()
{
// Arrange
Area area1 = new Area { Name = "Area 1" };
Area area2 = new Area { Name = "Area 2" };
using (ISession session = SessionFactory.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
session.Save(area1);
session.Save(area2);
transaction.Commit();
}
}
int resultCount;
// Act
using (ISession session = SessionFactory.OpenSession())
{
Area existingArea;
using (var transaction = session.BeginTransaction())
{
existingArea = session.Get<Area>(area1.ID);
}
existingArea.Name = area2.Name;
using (var transaction = session.BeginTransaction())
{
resultCount = session.CreateCriteria<Area>().Add(Restrictions.Eq("Name", existingArea.Name)).List<Area>().Count;
}
}
// Assert
Assert.AreEqual(1, resultCount);
}
I’ve found what I need:
The problem was caused because the default FlushMode (FlushMode.Auto) will sometimes flush changes to the database before queries to prevent stale reads.
By changing to FlushMode.Commit it only writes changes to the database when commit is called which suits my needs.
Thanks for your help gillyb.