NHibernate linq queries for updates don't respect the commit transaction

61 Views Asked by At

I'd like to update entities using linq queries provided by NHibernate. For example (from the official doc)

session.Query<Cat>()
    .Where(c => c.BodyWeight > 20)
    .UpdateBuilder()
    .Set(c => c.BodyWeight, c => c.BodyWeight / 2)
    .Update();

I noticed this statement execute immediately the update before the commit of the transaction.

There are two problems.

First. How the rollback is correctly managed?

Second. Imaging this scenario. Two entities and there is a constraint on a column. The first entity column has A1 value, the second entity column is has A2 value.

Updating in a foreach in this way there is a problem. The first entity column is modified assuming A2 value, the second entity column is modified assuming A1 value. Updating in this way the database raise an exception of constraint violated at the first updating.

How can I solve that? Maybe a batch way?

Thanks in advance

1

There are 1 best solutions below

2
Firo On

The update it issued immediatly as part of the transaction. If the transaction is rolled back the update will be rolled back as well.

As for your second question. Keys/Ids are supposed to be immutable. If they are needed to change then disable contraints while updating them and enable them afterwards. Here an example for MSSQL