Profile picture Schedule a Meeting
c a n d l a n d . n e t

Nhibernate Many-to-many mapping with an Enumeration on One Side

Dusty Candland | |

I’m posting this because I was trying to do this in an intuitive way and was thinking about it in the wrong way. A post on StackOverflow,  Map to a list of enums, got me pointed in the right direction.

I prefer using Enum’s in code, in place of database lookup tables, doing this for single properties, it makes sense to just map the Enum value into the database column of the owning entity. However when thinking about mapping many-to-many, for example, the US States a person has visited, and you fall into DB thinking mode. Many-to-many is the solution, unless States is an Enum and that’s all you need. In that case you should think about the problem for the domain side, a person as a list of visited States. In this way, you only need to have a one-to-many relationship, where the many side is the Enum value.

Adding something like the mapping code below to you Person mapping will get a VisitedStates table with a PersonId column and StateId column. No lookup tables needed, of course one could be added to help the DBAs. In the code you have a States list on the Person class.

Advantages

  • No mapping table.
  • Lookup data defined in code, as an Enumeration.
  • Less classes and mapping files.
  • Don’t have to worry about updating a lookup table with new values.
  • Don’t have to worry about making a State class with a immutable mapping.

Disadvantages

  • DBAs won’t know the values without maintaining a lookup table (even if it doesn’t get used by code).
  • Can not reorder the Enumeration values without updating the DB.

Other advantages/disadvantages?

Webmentions

These are webmentions via the IndieWeb and webmention.io. Mention this post from your site: