c# - Receiving stale data from NHibernate when going through a web service

问题描述:

I'm having trouble grasping some of the features of NHibernates caching / database-hit-prevention techniques.

I've created a test case which is supposed to ensure that our web service API properly creates and saves a new object. The test case passes fine when I do not have to serialize through the web service (e.g. directly working with the web service class instead of adding it as a service reference and going up/down through it). However, I receive stale data from NHibernate when I run my test case against the hosted web service.

//Call TaskDto.Create to convert Task into TaskDto for client-side use.

return TaskDto.Create(taskAction.CreateTask());

}

catch (Exception exception)

{

Logger.Error(exception);

throw;

}

}

The GetAll() method is simply a criteria.List() for all rows in a table. The CreateTask method just calls ISession.SaveOrUpdate();

I understand that I have the ability to force reloading data, but I do not understand why I should have to do this.

When I call SaveOrUpdate(entity), that entity should automatically be added to NHibernate's cache, right? Why would TaskDao.GetAll() return stale data?

I am worried about overusing CommitTransaction(). I do not think that I should call CommitTransaction() after every SaveOrUpdate() -- that defeats the purpose of NHibernates caching. But, I do not want stale data for my test cases, either. How can I keep my cache in sync?

网友答案:

You are correct in that you should not commit your transaction after every save but your web service should be creating a new transaction at the start of the web call and committing at the end of the web call.

Web services typically follow the same session per request pattern that web sites typically follow so ensure that your web service infrastructure is creating both a new NHibernate ISession and starting a new transaction with each request. At the end of that request, it should be committing any changes made.