开发者

Nhibernate one-to-many association

I have such a simple model:

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; }
}

Then I have such mappings:

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 clas开发者_运维百科s="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>

How do I map one-to-many association (unidirectional)?

Thanks!


In the blog mapping file you need to define a one-to-many relation between the foreign key column that references the Blog entity in the post table say it is BlogId and you need to tell'em what class this one-to-many relation relates to, in your case this will be the Post class and you need to define it with it's fully qualified namespace that contains this class and a comma then the assembly name as following:

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


I think it's the same problem as described here.

And also, I think you have a mistake in mapping of the Post - class name shouldn't be Blog. Also, there's no relation from Post to Blog in your example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜