So, just last week I asked a question on how to handle many-to-many with extra columns nhibernate. Answer seemed pretty clear, just use the link table and make two many-to-one. However since I'm using Entity Developer to generate my model, I had a problem with that method...
Anyway, I continued my investigation on the many-to-many problem and found that maybe I could create some kind of composite element that would act a lot like a many-to-many, but with an extra property(!)
This would be the new model:
The mapping file for User looks like this:
<hibernate-mapping ...>
<class name="User" table="Users">
<id name="UId" type="Int32">...</id>
<property name="UserName" type="String">...</property>
<set name="Groups" table="UGLinks" inverse="true" generic="true">
<key>
<column name="UId" />
</key>
<composite-element class="UGLinkExtra">
<many-to-one name="Groups" class="Group" fetch="join">
<column name="GId" />
</many-to-one>
<property name="Date">
<column name="Date" not-null="true" />
</property>
</composite-element>
</set>
</class>
</hibernate-mapping>
So I have this Composite-element
that kind of simulates the many-to-many look but with a extra column property.
Let's say I have a User u
and a Group g
that I want to link. Then it's just a matter of
u.Groups.add(new UGLinkExtra() {Groups = g, Date = DateTime.Now});
And in NHibernate I also see that a link has been added (if I do u.Groups I get a list (of UGLinkExtra) where g is included), however I can't get it to save to the Database!
Even when I do session.SaveOrUpdate(u)
(or g, I have tried both) it never gets written to the database... Only SQL I see is:
NHibernate: SELECT this_.UId as UId0_0_, this_.UserName as UserName0_0_ FROM Users this_
NHibernate: SELECT this_.GId as GId2_0_, this_.GroupName as GroupName2_0_ FROM Groups this_