对于Post。主人,你应该把它映射成多对一。XML中的示例
<many-to-one name="Owner" lazy="false" column="OwnerId"/>
一对一映射将假设这两个实体具有相同的ID值。
还有一点需要注意,NH Mapping中的ForeignKey是指FK的名称,而不是外键列。
这里有一个友好的提示,你不需要同时拥有OwnerId和Owner属性。你所需要的只是业主的财产。您也不需要ParentId属性,但请确保在Post上设置了Inverse=false。回复
public class Post
{
public virtual long PostId { get; set; }
public virtual DateTime DatePosted { get; set; }
public virtual User Owner { get; set; }
public virtual ISet<Post> Replies { get; set; }
public Post()
{
Replies = new HashedSet<Post>();
}
}
public class User
{
public virtual long UserId { get; set; }
public virtual string LoginName { get; set; }
}
Post的地图
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
namespace="Mfs.Core"
assembly="Mfs.Core">
<class name="Post" table="tPost" lazy="false">
<id name="PostId">
<generator class="hilo"></generator>
</id>
<property name="DatePosted" type="timestamp"/>
<!--<one-to-one name="Owner" lazy="false" foreign-key="OwnerId"/>-->
<many-to-one name="Owner" lazy="false" column="OwnerId"/>
<set name="Replies" inverse="false" cascade="all-delete-orphan" lazy="false">
<key column="ParentId"/>
<one-to-many class="Post" />
</set>
</class>
</hibernate-mapping>
用户映射
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
namespace="Mfs.Core"
assembly="Mfs.Core">
<class name="User" table="tUser" lazy="false">
<id name="UserId">
<generator class="hilo"></generator>
</id>
<property name="LoginName"></property>
</class>
</hibernate-mapping>