Nhibernate事务锁定表

时间:2014-04-09 08:46:28

标签: c# nhibernate transactions

我开发了一个使用nHibernate的WCF api。我是新来的。我使用session.update来处理事务。我有一个for循环,其中基于选择条件我正在更新记录即。如果tabel1中存在A,那么我正在更新表,否则插入一个新条目。

我收到“无法执行查询”。尝试通过在表中添加新条目来对先前正在更新的表执行选择查询时。

我的想法是,因为我正在使用session.save(table1),然后尝试从该表中选择条目,我收到一个错误。由于session.save临时锁定表,因此我无法在该表上执行select查询。

这可以解决这个问题吗?

更新: 这个for循环用于检查数据库中的某些字段:

using (ITransaction tranx = session.BeginTransaction())
{
   savefunction();
   tranx.Commit();
}

保存功能:

public void savefunction()
{
    for (int i = 0; i < dictionary.Count; i++)
    {             
                    ICandidateAttachmentManager candidateAttach = new ManagerFactory().GetCandidateAttachmentManager();
                    CandidateAttachment attach = new CandidateAttachment();
                    attach = checkCV();
         if(attach == null)
         {
           //insert new entry into table attach
            session.save(attach);
         }
      }
}

checkCV功能:

public void checkCV()
{
        using (ICandidateAttachmentManager CandidateAttachmentManager = new ManagerFactory().GetCandidateAttachmentManager())
        {
           IList<CandidateAttachment> lstCandidateAttachment = CandidateAttachmentManager.GetByfkCandidateId(CandidateId);
            if (lstCandidateAttachment.Count > 0)
            {
                CandidateAttachment attach = lstCandidateAttachment.Where(x => x.CandidateAttachementType.Id.Equals(FileType)).FirstOrDefault();
                if (attach != null)
                {
                   return null;
                }
                else
                {
                   return "some string";
                }
            }
        }
}

这里发生的是for循环,如果说i = 2,则附加值为null,表示我正在输入附加表中的新条目。然后当i = 3时,当它进入checkCV函数时,我在这一行得到一个错误:

  

IList lstCandidateAttachment =   CandidateAttachmentManager.GetByfkCandidateId(CandidateId);

我认为这是因为我使用session.save然后尝试读取tabel内容我无法执行查询并且表被锁定直到我提交会话。在beginTransaction和commit之间,与该对象关联的表被锁定。我怎样才能做到这一点?任何想法?

更新 我读了一些帖子。看起来我需要为事务设置隔离级别。但即使添加后它似乎也无效。以下是我试图补充的方法:

 using (ITransaction tranx = session.BeginTransaction(IsolationLevel.ReadUncommitted))
 {
     saveDocument();
 }

1 个答案:

答案 0 :(得分:0)

我在您的代码中无法理解的内容是您获得nHibernate会话的地方。

确实你使用

    new ManagerFactory().GetCandidateAttachmentManager();

    using (ICandidateAttachmentManager CandidateAttachmentManager = new ManagerFactory().GetCandidateAttachmentManager())

所以你的ManagerFactory类为你提供了ISession?

然后你做:

    CandidateAttachment attach = new CandidateAttachment();
    attach = checkCV();

    checkCV() returns either a null or a string ?

最后你永远不应该做

    Save()

但是

    SaveOrUpdate()

希望能帮助您解决问题。

随意提供更多详情

相关问题