假设我使用以下代码在数据库中保存了一些权限:
RoleRepository roleRep = new RoleRepository();
Role role = new Role();
role.PermissionItems = Permission.GetList();
roleRep .SaveOrUpdate(role);
现在,我需要此代码在role.PermissionItems == null
时删除与角色关联的PermissionItem。
以下是代码:
RoleRepository roleRep = new RoleRepository();
Role role = roleRep.Get(roleId);
role.PermissionItems = null;
roleRep .SaveOrUpdate(role);
但这种情况并没有发生。
应对这种情况的正确方法是什么?
我应该更改什么/如何更改,hbm文件或持久代码?
public class Role
{
public virtual string RoleName { get; set; }
public virtual bool IsActive { get; set; }
public virtual IList<Permission> PermissionItems { get; set; }
}
<?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>
public class Permission
{
public virtual string MenuItemKey { get; set; }
public virtual int RoleID { get; set; }
public virtual Role Role { get; set; }
}
<?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>
......
public void SaveOrUpdate(T obj)
{
try
{
if (!_session.Transaction.IsActive)
{
_session.BeginTransaction();
_session.SaveOrUpdate(obj);
_session.Transaction.Commit();
_session.Flush();
}
else
{
throw new Exception(CustomErrorMessage.TransactionAlreayInProgress);
}
}
catch (Exception ex)
{
_session.Transaction.Rollback();
_session.Clear();
throw ex;
}
}
......
public class RoleRepository : Repository<Role>, IRoleRepository
{
}
答案 0 :(得分:3)
将角色映射更改为级联all-delete-orphan,以便删除孤立的权限记录:
<bag name="PermissionItems" table="Permission" cascade="all-delete-orphan" inverse="true">
并在集合上调用clear,而不是将其设置为null:
role.PermissionItems.Clear();
刷新会话时,将删除孤立的权限记录。
PS:存储库中的catch块应该调用throw;
而不是throw ex;
。