Is there a reason not to use dynamic-insert/dynamic-update for NHibernate? The only reason I ask is that it seems to be something that I would want enabled as the default, not as something I would have to configure.
Are there any gotchas to be aware of when using these dynamic properties?
For some entities, you may create an invalid state though dynamic updates. Let’s say you’ve got a
Classwith aBooleanPropertyAand a logically dependentIntegerPropertyB. If PropertyAisTrue, then PropertyBcan only be a negative number, while if PropertyAisFalse, then PropertyBcan only be a positive number.Let’s say that two users both interact with an instance of this class within a given time span. To start off, users Alice and Bob both materialize this class from the database, with the initial values of
A= True andB= -50User Alice changes
AtoFalseandBto 125, and commits it to the database. Now we have this situation:User Bob doesn’t change
A, but changesBto -75, then commits it to the database. If Dynamic updates are on, then NHibernate sees that Bob has only changedBto -75, and issues a dynamic update that only edits the value ofB. If you had SQL validation on the server to preventBfrom being negative unlessAwas true, you’d get a SQL error here, but let’s say that you haven’t reproduced all your business logic on your SQL tables. Here is the resulting data:Both Alice and Bob have valid states, but the Database is now in an invalid state! User Charlie comes along and tries to materialize this record:
Charlie would likely get a validation error from your application when NHibernate tried to set the B property of the new instance of your class.
So, when you have logically dependent properties, you must have some strategy in place for avoiding this situation. One possibility is to simply enable
select-before-updatefor this entity. This can result in some additional database calls and a little slower performance. Another is to utilize versioning in NHibernate, which would mean that when Bob tries to save his record, NHibernate’s insert query would not trigger any writes and throw a stale data exception (that can be gracefully handled). You also could codify the logical requirements of your class in the database, however you’ll then have to be cautious to make sure the database and the program both have the same codified requirements as time goes on, and you’ll have multiple places to make changes when requirements change, which isn’t always a worthwhile overhead.So in short, in many circumstances a developer must handle the details of dynamic-updates carefully, which is why it is not on by default. When you turn it on, consider if partial updates to your entity could cause problems, and if so, use one of the mitigating strategies I’ve recommended to protect against that issue.