views:

360

answers:

1

I would like to do the following, all in a single atomic transaction:

  1. Read an object through ActiveRecord
  2. Save a new object through ActiveRecord
  3. Update another table via NHibernate

Also, if by the time I finish the transaction, the value of the object I've read in step 1 has changed, I would like the transaction to fail.

I've never used transactions before in either AR or NH, so please supply as much details as you can. How do the transaction mechanisms play together?

+2  A: 

Well, Castle ActiveRecord depends on NHibernate. True, a Castle ActiveRecord Transaction class is not the same as the one found on NHibernate; but you should think of ActiveRecord's as a wrapper over the one in NHibernate.

So there is no need of "playing together". Because, deep down, they are the same.

Another important concept is that of "Session". A "session" is a unit of work, a "window" that you use to tell NHibernate what you want to do: queries, updates, inserts etc. Again, there is a NHibernate Session, and a Castle ActiveRecord Session too. Again, the latter is a wrapper over the first one.

This is important because when you're using a session in ActiveRecord (and in fact you always do, even if implicitly), it is possible to access the "hidden" NHibernate session inside it; usually using a delegate passed to the Execute method. And that's the way that you can use both styles of code inside your application (see the Execute Callback example here).

To get a better grasp of session meaning, see here.

Finally, I suggest that you always use ActiveRecord's style to declare sessions and transactions, even when mixing both styles of coding. Since they represent also NHibernate sessions and transactions, you are safe. To better understand that, please read here.

PS: Yep, I didn't write the example you asked for (too lazy for that), but I reckon it will be better for your learning process if you write it. Believe me, it's easier than you think.

rsenna