我目前使用 NHibernate 作为我的数据访问层,使用 Fluent NHibernate 为我创建映射文件。我有两个类,TripItem 和 TripItemAttributeValue,它们之间有一个多对多的关系。
映射如下:
public class TripItemMap : ClassMap<TripItem2>
{
public TripItemMap()
{
WithTable("TripItemsInt");
NotLazyLoaded();
Id(x => x.ID).GeneratedBy.Identity().WithUnsavedValue(0);
Map(x => x.CreateDate, "CreatedOn").CanNotBeNull();
Map(x => x.ModifyDate, "LastModified").CanNotBeNull();
/* snip */
HasManyToMany<TripItemAttributeValue>(x => x.Attributes).AsBag()
.WithTableName("TripItems_TripItemAttributeValues_Link")
.WithParentKeyColumn("TripItemId")
.WithChildKeyColumn("TripItemAttributeValueId")
.LazyLoad();
}
}
public class TripItemAttributeValueMap : ClassMap<TripItemAttributeValue>
{
public TripItemAttributeValueMap()
{
WithTable("TripItemAttributeValues");
Id(x => x.Id).GeneratedBy.Identity();
Map(x => x.Name).CanNotBeNull();
HasManyToMany<TripItem2>(x => x.TripItems).AsBag()
.WithTableName("TripItems_TripItemAttributeValues_Link")
.WithParentKeyColumn("TripItemAttributeValueId")
.WithChildKeyColumn("TripItemId")
.LazyLoad();
}
}
在我的应用程序的某个时刻,我从数据库中获取现有属性,将它们添加到tripItem.Attributes,然后保存tripItem 对象。最后,TripItems_TripItemAttributeValues_Link 永远不会得到任何新记录,导致关系没有被持久化。
如果有帮助,这些是 Fluent NHibernate 为这些类生成的映射文件:
<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-lazy="true" assembly="ETP.Core" namespace="ETP.Core.Domain">
<class name="TripItem2" table="TripItemsInt" xmlns="urn:nhibernate-mapping-2.2" lazy="false">
<id name="ID" column="ID" type="Int32" unsaved-value="0">
<generator class="identity" />
</id>
<property name="CreateDate" column="CreatedOn" type="DateTime" not-null="true">
<column name="CreatedOn" />
</property>
<property name="ModifyDate" column="LastModified" type="DateTime" not-null="true">
<column name="LastModified" />
</property>
<bag name="Attributes" lazy="true" table="TripItems_TripItemAttributeValues_Link">
<key column="TripItemId" />
<many-to-many column="TripItemAttributeValueId" class="ETP.Core.Domain.TripItemAttributeValue, ETP.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</bag>
</class>
</hibernate-mapping>
和
<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-lazy="true" assembly="ETP.Core" namespace="ETP.Core.Domain">
<class name="TripItemAttributeValue" table="TripItemAttributeValues" xmlns="urn:nhibernate-mapping-2.2">
<id name="Id" column="Id" type="Int32">
<generator class="identity" />
</id>
<property name="Name" column="Name" length="100" type="String" not-null="true">
<column name="Name" />
</property>
<bag name="TripItems" lazy="true" table="TripItems_TripItemAttributeValues_Link">
<key column="TripItemAttributeValueId" />
<many-to-many column="TripItemId" class="ETP.Core.Domain.TripItem2, ETP.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</bag>
</class>
</hibernate-mapping>
我在这里做错了什么?