I have two objects: Color and Palette. Each palette can get a range of colors assigned. That is what I am able to configure out with Fluent NHibernate without any problem.
But: the assignment of colors is only a constraint. If no color is assigned the palette should have every color which is available in the database.
My approach would be to check if Palette.Colors.Count() is 0, and if so, to fetch all the colors by ColorRepository.GetAllColors() and assign them manually to the palette.
Is there another “built-in” way?
It will be difficult (read: impossible) for NHibernate to map something that the database does not reflect.
You would get a huge headache if you assigned all available colors to the palette if no color is assigned. Before persisting you would have to empty the list, so that you do not end up with all those colors in the PaletteColorAssociation table.
The way I understand you, I see two options here:
1) Turn the whole thing around. What I mean is, do not save the colors that are assigned but those that are not assigned. Make that a PaletteColorExclusion table. Of course there are drawbacks to this: 1) If you add a new color to your Colors table, then that color will implicitly be part of every palette and 2) If your general rule is to only have a fraction of the available colors assigned to a palette, you will end up with more rows in the table that you would need.
I do not recommend that approach. It is only meant to show a way how to reflect that logic in the DB.
2) A modification of your apporach seems like the better idea: Do not put that logic within the Palette class but in your business logic classes. Example:
I did not test that code and I put
ReadOnlyCollectionthere to avoid the temptation of altering the collection, since it may not be the palette’s colors.