【发布时间】:2014-04-03 22:47:27
【问题描述】:
所以,就在上周,我问了一个关于如何处理many-to-many with extra columns nhibernate 的问题。答案似乎很清楚,只需使用链接表并进行两个多对一。 但是,由于我使用 Entity Developer 来生成我的模型,所以我在使用该方法时遇到了问题...
无论如何,我继续研究多对多问题,发现也许我可以创建某种复合元素,它的行为很像多对多,但具有额外的属性(!)
这将是新模型:
User 的映射文件如下所示:
<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>
所以我有这个Composite-element,它模拟了多对多的外观,但有一个额外的列属性。
假设我有一个 User u 和一个 Group g 我想链接。那么这只是一个问题
u.Groups.add(new UGLinkExtra() {Groups = g, Date = DateTime.Now});
在 NHibernate 中,我还看到添加了一个链接(如果我添加了 u.Groups,我会得到一个包含 g 的(UGLinkExtra)列表),但是我无法将它保存到数据库中!
即使我这样做session.SaveOrUpdate(u)(或g,我都尝试过)它永远不会被写入数据库......我看到的只有SQL:
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_
【问题讨论】:
标签: c# nhibernate