nhibernate中的一对多映射但无法在子实体的数据表中保存父亲的ID

时间:2013-06-10 03:25:13

标签: nhibernate

如果有人可以帮助我?为什么执行测试代码后字段fatherid的值为null? 1)父实体定义:

class father
{
   public virtual string name;
   public virtual string id;
   public virtual IList<child> children;
}

2)子实体定义:

class child
{
   public virtual string id;
   public virtual string name;
}

3)父亲的映射文件

<class name ="father" table="dbfather">
<id name="id" column ="id">
  <generator class ="assigned"/>
</id>
<property name ="name"/>
<bag name="ichild">
<key column="fatherid" />
<one-to-many class="child" />
</bag>
</class>

4)孩子的映射文件

<class name ="child" table="dbchild">
<id name="id" column ="id">
  <generator class ="assigned"/>
</id>
<property name ="name"/>
</class>

5)测试代码

var cfg = new NHibernate.Cfg.Configuration().Configure("hibernate.cfg.xml");
        using (ISessionFactory sessionFactory = cfg.BuildSessionFactory())
        {
            ISession session = sessionFactory.OpenSession();
            try
            {
                Child c = new Child();
                c.id= Guid.NewGuid().ToString();
                c.name= "test"; 
                Father f = new Father();
                f.id = Guid.NewGuid().ToString();
                f.name= "ftest";
                f.children.Add(child); 

                session.Save(c);
                session.Save(f);
            }
            finally
            {
                session.Flush();
            }
        }

1 个答案:

答案 0 :(得分:0)

public virtual IList<string> children;

应该是

public virtual IList<Child> children;