我知道对于多部分写入,我应该在 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.
(顺便说一句,如果您正在认真地进行 NHibernate 工作,请考虑试用 NHProf)。
关于c# - 我是否应该始终在 nhibernate 中使用事务(即使是简单的读写)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3304347/