tags:

views:

140

answers:

1

I have a reference/lookup table whose main purpose is to provide the user with a list of existing options. The user will also have the ability to enter new items into the list. How would you map this in NHibernate?

For example, say I have an Address class with a City field. The database has an Address table and a City lookup table. (I can define the relationships however I want at this point.) When editing the address:

  • The user can select any available City, or can enter a new City.
  • A new city entered must be added to the lookup table.
  • Editing an Address instance's city should either change the reference - if the edited city also exists in the DB - or create a new City entry by that name and refer to it. (If I edit "Chicago" to "New York", I don't want all addresses in Chicago to change to New York; just the one I'm looking at.)

I've been scouring NHib docs, and I'm not at all sure what approach I should take.

EDIT:

Part of my issue stems from the fact that I'm trying to avoid creating a "City" class with a single property - I'd just like Address.City to be a string in the domain model. This may be unwise, I don't know.

+1  A: 

So you have addresses and you want a distinct list of cities. You'll either need to do the "distinct" operation in your code or in the database. Doing it in code implies a City class mapped onto your City table - I can't see how you can avoid it.

If the "distinct" operation is done it the database, you'll need write sprocs to insert and update an Address. These sprocs would then contain the logic of "use the City if it's in the table, otherwise create a new one".

Personally I'm not in favour of sprocs if they can be avoided and so I'd recommend that you create a City class and map it with a on your Address class.

John Rayner
In the end, I'm going to stick with a String property, lose the lookup table, and populate the list using an HQL query. Thanks for the thoughts - selected your answer cause it was most helpful.
Remi Despres-Smyth