开发者

Mapping an instance of IList in NHibernate

I'm trying to map a parent-child relationship using NHibernate (2.1.2), MySql.Data (6.2.2) and MySQL Server (5.1). I figured out that this must be done using a <bag> in the mapping file. I build a test app which is running without yielding any errors and is doing an insert for each entry but somehow the foreign key inside the children table (ParentId) is always empty (null).

Here are the important parts of my code...

Parent

public class Parent
{
    public virtual int Id { get; set; }
    public virtual IList<Child> Children { get; set; }
}


<class name="Parent">
  <id name="Id">
    <generator class="native"/>
  </id>        
  <bag name="Children" cascade="all">
    <key column="ParentId"/>
    <one-to-many class="Child"/>
  </bag>    
</class>

Child

public class Child
{
    public virtual int Id { get; set; }
}

<class name="Child">
  <id name="Id">
    <generator class="native"/>
  </id>    
</class>

Program

using (ISession session = sessionFactory.OpenSession())
{                                
     session.Save(
      开发者_JAVA技巧  new Parent() 
        {
            Children = new List<Child>() 
            { 
                new Child(), 
                new Child() 
            } 
        });
}

Any ideas what I did wrong?


You must wrap all your data access in a transaction. This will work:

using (ISession session = sessionFactory.OpenSession())
using (ITransaction tx = session.BeginTransaction())
{                                
     session.Save(
        new Parent() 
        {
            Children = new List<Child>() 
            { 
                new Child(), 
                new Child() 
            } 
        });
     tx.Commit();
}

In fact, the inserts are only being performed because you're using a native generator; with a client-side generator they wouldn't even be sent to the DB.


<class name="Child">
  <id name="Id">
    <generator class="native"/>
  </id>    
  <many-to-one name="Parent" column="ParentID"/>
</class>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜