开发者

NHibernate not updating child entity

开发者 https://www.devze.com 2023-03-19 23:20 出处:网络
I am facing a problem when trying to update a child item in Parent class public class Parent { public virtual int Id { get; set; }

I am facing a problem when trying to update a child item in Parent class

public class Parent
    {
        public virtual int Id { get; set; }
        public virtual string Name { get; set; }
        public virtual IList<Child> MyChildren { get; set; }
    }
    public class Child
    {
        public virtual int Id { get; set; }
        public virtual string Name { get; set; }
        public virtual Parent MyParent { get; set; }
    }

What i do is to take one item of the MyChildren list and modify it, but when calling SaveOrUpd开发者_如何学Cate Method from Session MyClildren is not being saved.

Note: if other fields in parent are modified it get updated in DB.

Update:

<class name="Parent" table="Parent" lazy="true">
    <id name="id" column="ID" type="int">
      <generator class="identity" />
    </id>

      <bag cascade="all" lazy="true" name="MyChildren">
        <key column="ID"/>
        <one-to-many class="SND.Domain.Model.Child" />
      </bag>
</class>

<class name="Child" table="Child" lazy="true">
    <id name="id" column="ID" type="int">
      <generator class="identity" />
    </id>
    <!-- Here i have another reference -->
     <many-to-one name="AnotherEntity" class="SND.Domain.Model.AnotherEntity" column="entity_ID"/>

    <property name="Name" column="Name" type="string" not-null="false" />
</class>

Thanks, Pedro


I can't see your mapping file, but do you have the cascade attribute on your child collection set in the parent mapping file?


It's a mapping trouble I think, try this :

<bag  generic="true" cascade="all" inverse="false" name="MyChildren">
    <key column="ID"/>
    <one-to-many class="SND.Domain.Model.Child" />
</bag>

Update1

using (var session = SessionFactory.OpenSession())
using (var tx = session.BeginTransaction())
{

    session.SaveOrUpdate( ... );
    tx.Commit();
}
0

精彩评论

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

关注公众号