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开发者_如何学Go.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:
session.FlushMode = FlushMode.Commit;
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.
All changes you make within the session are persistent across the session. So inside a session, there is no way to know what data was changed earlier in the session and what data matches the database schema.
You could try to workaround this by having two different sessions open. In one of them don't make any changes, and then you'll always know with what you started out with.
...Or, if there are specific spots in the application where you need history tracking, I would create some kind of history table where you save every change to certain items that you want to track. I think this solution would be the best, but then again, it all depends on what your specific needs are.
精彩评论