mrblah
mrblah

Reputation: 103517

how to commit and start a new transaction within a single request?

I am using the repository pattern in nhibernate. In a asp.net mvc application. I have a httpmodule, that:

beginRequest it calls session.beginTransaction();
EndRequest it calls session.Transaction.Commit();

This is fine for 95% of the time.

I have a case where I need to do the following in a single request:

List<User> users = factory.getUsers();

// update users

// commit transaction

// load users from the db again

Should I just call:

factory.Session.Transaction.Commit();
factory.Session.BeginTransaction();

I know this is one of the reasons against using the Repository pattern, and having the Session start/end in a HttpModule, but anyway that is how I am doing it :)

What are my options?

Uptate So basically I will now have:

A page request will look like:

BeginRequest:  Session.BeginTransaction();

userlist.aspx:   
               // code to fetch users from the db
               // update users
               Session.Transaction.Commit();
               Session.BeginTransaction();
               // code to fetch recently commited users form db

EndRequest:    Session.Transaction.Commit();

Does the above seem correct?

I guess I should also first check if there is a current transaction before calling commit and begin again?

Upvotes: 0

Views: 309

Answers (1)

djna
djna

Reputation: 55907

You have two pieces of logic

List<User> users = factory.getUsers();

// update users

and

load users

and you want those to be in separate transactions. So you add the appropriate Starts and Commits. It works, where's the problem?

having the Session start/end in a HttpModule, but anyway that is how I am doing it :) What are my options?

Is the point of the discussion whether to have Session start end in HttpModule? Well, your options is not to do it! You have a block of logic (admitedly here very simple logic) potentially it's reusable so move it to its own class. Do you think it's better to have

client code:

  useSomeLogic() // bzzzt forgot to start session

  startSession()
  useSomeLogic()  // ok thank you, I can work, but please remember to commit
  commit()

Or

  useSomeLogic() // just fine, I'll start the session and do you work for you and commit

I like nicely packaged reusable code, and that's why I refactor things away from transport-specific modules.

Upvotes: 1

Related Questions