简体   繁体   English

Nhibernate返回错误的结果

[英]Nhibernate returns wrong results

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. 返回正确的行, 但是 ,返回的对象将其属性ContainerId设置为一个非空的值,以便抛出异常。 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. 编辑在我在查询之前添加m_session.Flush()之后问题似乎消失了。 Still have no idea what goes wrong. 仍然不知道出了什么问题。

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. nhibernate和会话生命周期管理的研究工作单位。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM