Nhibernate一对多关联

时间:2011-10-15 10:05:23

标签: nhibernate nhibernate-mapping associations one-to-many

我有这么简单的模型:

public abstract class Entity
{
    public virtual Guid Id { get; protected set;  }
}

public class Post : Entity
{
    public String Title { get ; set; }
    public String Content { get; set; }
    public DateTime Timestamp { get; set; }
    public Byte[] Thumbnail { get; set; }
}

public class Blog : Entity
{   
    public String Title { get; set; }
    public ISet<Post> Posts { get; set; }
}

然后我有这样的映射:

BLOG

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" auto-import="true assembly="Application.Domain" namespace="Application.Domain.Entities">
  <class name="Blog">
    <!-- id generator -->
    <id name="Id">
      <generator class="guid.comb" />
    </id>
  <!-- properties/columns -->
  <property name="Title" not-null="true" />
  <!-- components/columns -->
  <!-- associations -->
  <set name="Posts" cascade="all">
     <!-- key column? -->       
  </set>
  </class>
</hibernate-mapping>

POST

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" auto-import="true" assembly="Application.Domain" namespace="Application.Domain.Entities">
  <class name="Blog">
    <!-- id generator -->
    <id name="Id">
      <generator class="guid.comb" />
    </id>
    <!-- properties/columns -->
    <property name="Title" not-null="true" />
    <property name="Content" not-null="true" />
    <property name="Timestamp" not-null="true"/>
    <property name="Thmbnail" />
    <!-- components/columns -->
    <!-- associations -->
  </class>
</hibernate-mapping>

如何映射一对多关联(单向)?

谢谢!

2 个答案:

答案 0 :(得分:1)

我认为这与描述here的问题相同。

而且,我认为你在Post-class名称的映射中有一个错误,不应该是Blog。此外,在您的示例中,Post与Blog没有任何关系。

答案 1 :(得分:1)

在博客映射文件中,您需要在引用表中引用one-to-many实体的外键列之间定义Blog关系,并说明它是BlogId,您需要告诉它这个一对多关系与哪个类相关,在你的情况下,这将是Post类,你需要用它的完全限定的命名空间来定义它,它包含这个类和一个逗号,然后汇编名称为以下内容:

<set name="Posts" table="Post">
  <key column="BlogId"/>
  <one-to-many class="Application.Domain.Entities.Post, Application.Domain"/>
</set>