NHibernate Master-Detail and Detail Deletion.

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:23 UTC
Read the original article Hit count: 706

Filed under:
|

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>

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

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

Now, I need this code to delete all Permissions, since role.Permissions == null. Here is the code:

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

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?

© Stack Overflow or respective owner

Related posts about nhibernate

Related posts about child