5

MVC アプリケーションでアクションを実行しid、人の名前を返します。

そのためのベストプラクティスは何ですか?私はNHProfのヒントに従っていますが、コードは少し奇妙に聞こえます。

using (var session = Helper.SessionFactory.OpenStatelessSession())
{
    using (var tran = session.BeginTransaction(IsolationLevel.ReadCommitted))
    {
        return session.Query<Person>().Where(x => x.Id == id).Select(x => x.Name).SingleOrDefault();
        tran.Rollback();
    }
}
4

3 に答える 3

4

The NHProf alert page explains it quite well I think -

http://nhprof.com/Learn/Alerts/DoNotUseImplicitTransactions

Basically it's saying if you don't manage transactions yourself, the database will create an "implicit transaction" and auto-commit for every statement, including queries. The misconception is that transactions are useful only for insert / update operations.

In your example above, it's not much of an issue as your transaction only executes a single statement anyway. If your method was running several statements however it would be good practice to wrap them in a transaction.

于 2012-05-10T13:12:42.627 に答える
0

1 つの HTTP リクエストで複数のセッションを作成しないでください。理想的には、リクエスト スコープでセッションと対応するトランザクションを開き、すべてのアクションでこのセッションを使用する必要があります。

これを達成する方法を説明するブログ投稿は次のとおりです。http://hackingon.net/post/NHibernate-Session-Per-Request-with-ASPNET-MVC.aspx

IOC コンテナーの使用をお勧めします。セッションを作成するクラスを作成し、このクラスをリクエスト スコープにスコープします。

ウェブ上には、この問題に取り組むためのリソースがたくさんあります。Google で検索してください。

于 2012-05-10T17:27:02.687 に答える
0

以下は、この選択にアプローチする方法です。

    using (var session = Helper.SessionFactory.OpenStatelessSession())
    using (var tran = session.BeginTransaction(IsolationLevel.ReadCommitted))
    {
        try
        {
            string personName = session.Query<Person>()
            .Where(x => x.Id == id)
            .Single(x => x.Name);

            tran.Commit();
            return personName;
        }
        catch(Exception ex)
        {
            // handle exception
            tran.Rollback();
        }
    }

この SO の回答は、トランザクションコミットを処理するための良いアドバイスを提供します:

NHibernate - ITransaction.Commit は本当に必要ですか?

LINQ に関しては、これは、拡張メソッド スタイルの構文を使用してクエリにアプローチしない方法に関する興味深い記事です。

http://compiledexperience.com/blog/posts/how-not-to-use-linq

于 2012-05-10T13:22:35.507 に答える