pq.
pq.

Reputation: 13

Unmapped Columns in NHibernate?

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...).

Upvotes: 1

Views: 1893

Answers (5)

Valentin Kuzub
Valentin Kuzub

Reputation: 12073

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.

Upvotes: 0

Firo
Firo

Reputation: 30803

there is an alternative which uses IPropertyAccessor interface see http://elegantcode.com/2009/07/13/using-nhibernate-for-legacy-databases/

Upvotes: 0

Stuart Childs
Stuart Childs

Reputation: 3305

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.

Upvotes: 5

gcores
gcores

Reputation: 12656

THe NHibernate answer is to implement IInterceptor.

Upvotes: 0

Michael Pralow
Michael Pralow

Reputation: 6630

you could go with custom CRUD sql, in java i'd say a private setter with default value for the attribute would work too

Upvotes: 1

Related Questions