Reputation: 434
I have this code:
lock (m_session)
{
var _result = m_session.Query<StaticContainerStorage>().Where(c => c.StorageId == storageName && c.ContainerId == null).FirstOrDefault();
if (!String.IsNullOrEmpty(_result.ContainerId))
throw new Exception();
if (_result == null)
{
_result = new StaticContainerStorage(storageName, 0);
AddContainer(_result);
}
return _result;
}
which results in this query:
select TOP (1) mfccontain0_.ID as ID0_,
mfccontain0_.StorageId as StorageId0_,
mfccontain0_.StorageIndex as StorageI3_0_,
mfccontain0_.ContainerId as Containe4_0_
from dbo.[MfcContainerStorage] mfccontain0_
where mfccontain0_.StorageId=@p0 and (mfccontain0_.ContainerId is null)
which returns a correct row, but, the returned object has its property ContainerId set to a value, which is not null, so that the exception is thrown. What happens here? I have multiple threads accessing that method, that's why it is locked to a (single) session.
Any ideas?
EDIT
The problem seems to be gone after I added m_session.Flush()
before the query. Still have no idea what goes wrong.
Upvotes: 0
Views: 606
Reputation: 200
You are using lock around the session which suggests you are either using one session for the life of the app, or you are reusing a session which is not good practice.
You are having to manually flush to allow the session to update from previous changes, the flush will issue outstanding inserts and updates.
You should be wrapping all queries and updates in a session transaction. On commit it will flush automatically, but also it will allow caching, batch processing and future queries to work correctly.
Research unit of work for nhibernate and session life cycle management.
Upvotes: 2