NHibernate child deletion problem.

Posted by JMSA on Stack Overflow See other posts from Stack Overflow or by JMSA
Published on 2010-04-13T07:17:55Z Indexed on 2010/04/13 7:53 UTC
Read the original article Hit count: 223

Filed under:
|
|

Suppose, I have saved some permissions in the database by using this code:

RoleRepository roleRep = new RoleRepository();
Role role = new Role();
role.PermissionItems = Permission.GetList();
roleRep .SaveOrUpdate(role);

Now, I need this code to delete the PermissionItem(s) associated with a Role when role.PermissionItems == null.

Here is the code:

RoleRepository roleRep = new RoleRepository();
Role role = roleRep.Get(roleId);
role.PermissionItems = null;
roleRep .SaveOrUpdate(role);

But this is not happening.

What should be the correct way to cope with this situation?

What/how should I change, hbm-file or persistance code?

alt text

Role.cs

public class Role
{
    public virtual string RoleName { get; set; }
    public virtual bool IsActive { get; set; }
    public virtual IList<Permission> PermissionItems { get; set; }
}

Role.hbm.xml

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="POCO" namespace="POCO">
  <class name="Role" table="Role">
    <id name="ID" column="ID">
      <generator class="native" />
    </id>    
    <property name="RoleName" column="RoleName" />
    <property name="IsActive" column="IsActive" type="System.Boolean" />
    <bag name="PermissionItems" table="Permission" cascade="all" inverse="true">
      <key column="RoleID"/>
      <one-to-many class="Permission" />
    </bag>    
  </class>  
</hibernate-mapping>

Permission.cs

public class Permission
{
    public virtual string MenuItemKey { get; set; }
    public virtual int RoleID { get; set; }
    public virtual Role Role { get; set; }
}

Permission.hbm.xml

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="POCO" namespace="POCO">
  <class name="Permission" table="Permission">
    <id name="ID" column="ID">
      <generator class="native"/>
    </id>
    <property name="MenuItemKey" column="MenuItemKey" />
    <property name="RoleID" column="RoleID" />
    <many-to-one name="Role" column="RoleID" not-null="true" cascade="all">      
    </many-to-one>
  </class>
</hibernate-mapping>

© Stack Overflow or respective owner

Related posts about c#

Related posts about nhibernate