c# – 我应该总是使用nhibernate中的事务(即使是简单的读写)?

前端之家收集整理的这篇文章主要介绍了c# – 我应该总是使用nhibernate中的事务(即使是简单的读写)?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我知道对于多部分写,我应该在nhibernate中使用事务.然而,对于简单的读取和写入(1部分​​)…我已经看到,始终使用事务是个好习惯.这是否需要?

我应该如何做一个简单的阅读?或者我可以把转录部分放在一起吗?

public PrinterJob RetrievePrinterJobById(Guid id)
{
    using (ISession session = sessionFactory.OpenSession())
    {
        using (ITransaction transaction = session.BeginTransaction())
        {
            var printerJob2 = (PrinterJob) session.Get(typeof (PrinterJob),id);
            transaction.Commit();

            return printerJob2;
        }
    }  
}

要么

public PrinterJob RetrievePrinterJobById(Guid id)
{
    using (ISession session = sessionFactory.OpenSession())
    {
        return (PrinterJob) session.Get(typeof (PrinterJob),id);              
    }
}

对于简单的写作呢?

public void AddPrintJob(PrinterJob printerJob)
{
    using (ISession session = sessionFactory.OpenSession())
    {
        using (ITransaction transaction = session.BeginTransaction())
        {
            session.Save(printerJob);
            transaction.Commit();
        }
    }
}

解决方法

最佳建议是始终使用交易. This link from the NHProf文档,最好的解释为什么.

When we don’t define our own
transactions,it falls back into
implicit transaction mode,where every
statement to the database runs in its
own transaction,resulting in a large
performance cost (database time to
build and tear down transactions),and
reduced consistency.

Even if we are only reading data,we
should use a transaction,because
using transactions ensures that we get
consistent results from the database.
NHibernate assumes that all access to
the database is done under a
transaction,and strongly discourages
any use of the session without a
transaction.

(BTW,如果您正在严格的NHibernate工作,请考虑尝试NHProf).

原文链接:https://www.f2er.com/csharp/97735.html

猜你在找的C#相关文章