views:

1142

answers:

2

I have a model where multiple classes have a list of value types:

class Foo { public List<ValType> Vals; }
class Bar { public List<ValType> Vals; }

Foo and Bar are unrelated apart from that they both contain these vals. The rules for adding, removing, etc. the ValTypes are different for each class. I'd like to keep this design in my code.

There are times when I want to copy some Vals from a Foo to a Bar, for example. In the database, each ValType has its own table, to keep it small, light (it just has the parent ID + 2 fields), and allow integrity checks. I know NHibernate says I should keep my objects as granular as the database, but that just makes my code uglier.

The best I've thought of so far is to make separate subclasses of ValType, one for each parent. Then I can map those at that level. Then, I'll hook up add and remove logic to auto-convert between the right subclasses, and actually store them in a private list that has the right subclass type. But this seemed a bit convoluted.

How can I map this in NHibernate (Fluent NHibernate if possible)?

Please let me know if this is a duplicate -- I'm not quite sure how to search this.

+2  A: 

At database level a solution would be to have:

Val(Id)
Bar(Id)
BarToVal(IdBar, IdVal)
FooToVal(IdFoo, IdVal)

I am not very sure how would these be mapped. Maybe something like:

// BarMap:  
HasManyToMany(x => x.Vals).WithTableName("BarToVal");

// FooMap:  
HasManyToMany(x => x.Vals).WithTableName("FooToVal");

Hope it's making sense...

Aleris
Yea, I would do it that way except it's a bit of a performance hit. The tables are very small (20 bytes), and the PK is all the columns (ForeignID, Field1, Field2)
MichaelGG
+1  A: 

You can find an example on the Google Code page for Fluent NHibernate.

Ryan Riley
Hmm that'd be embarrassing :P. I'll check it out!
MichaelGG
I see the link does not exist anymore, would like to see the solution
adriaanp