I'm working with a legacy database in Oracle and some of my tables have columns that are set to NOT-NULL that I don't want in my domain model, but, obviously, I need to specify somewhere that at least some default value is saved to the database (eg a Groups table may have a "Indentation" column thaqt always expects a char(8) value).
How would I go about this in NHibernate? Is there an "easy" way to do this? If not, does anyone know of a way I could do this (I've thought about using an Inteceptor, but really wouldn't know where to start...). I can't change the database schema so this, sadly, isn't an option (fluent versions are ok too...).
If you don't want to pollute your POCOs, an Interceptor probably is the best option. Take a look at various articles about interceptors, like this one.
On your interceptor, you'd want to check the type so you know which fields to put dummy data in. Make sure you use currentState[] in the OnFlushDirty method (OnFlushDirty is "update") and state[] in the OnSave method ("insert"). For example (OnSave):
if (entity is Group)
{
state[Array.IndexOf(propertyNames, "Indentation")] = "dummy value";
return true;
}
return false;
Edit:
You're trying to insert data that doesn't exist in your domain but is required by your database model, so the above wouldn't quite work for you. Instead, you'll have to add an element to each of the state, propertyNames, and types arrays.
you could go with custom CRUD sql, in java i'd say a private setter with default value for the attribute would work too
THe NHibernate answer is to implement IInterceptor.
there is an alternative which uses IPropertyAccessor interface
see http://elegantcode.com/2009/07/13/using-nhibernate-for-legacy-databases/
I always thought this kind of problems is best resolved with specifying a default value for a column.
That way you can forget about it whatsoever and not implement some Interceptor, which even sounds scary.
Heres sample SQL code: alter table with default value
I am guessing that even though DB is legacy, you got some control over it since you can insert new rows. This is very cheap and lightweight solution.