我有2个实体用户和角色
Role.hbm.xml:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
namespace="UserManagmentStudio.Domain.Model"
assembly="UserManagmentStudio.Domain">
<class name="Role" table="Roles" lazy="true" dynamic-update="false">
<id name="Id" column="Id" type="int">
<generator class="identity" />
</id>
<property name="Name" not-null="true" length="50" />
<set name="Users" table="UsersInRoles" fetch="subselect" lazy="extra" cascade="delete">
<key column="RoleId"/>
<many-to-many column="UserId" class="User"/>
</set>
</class>
</hibernate-mapping>
User.hbm.sql:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
namespace="UserManagmentStudio.Domain.Model"
assembly="UserManagmentStudio.Domain">
<class name="User" table="Users" dynamic-update="false">
<id name="Id" column="Id" type="int">
<generator class="identity" />
</id>
<property name="Password" not-null="true" length="50"/>
<property name="FirstName" not-null="true" length="50"/>
<property name="LastName" not-null="true" length="50"/>
<property name="Login" not-null="true" length="50"/>
<property name="Birthday" not-null="true"/>
<property name="IsActive" not-null="true" />
<property name="RegistrationDate" not-null="true" />
<set name="Roles" table="UsersInRoles" fetch="subselect" lazy="extra" cascade="none" >
<key column="UserId" />
<many-to-many column="RoleId" class="Role"/>
</set>
</class>
</hibernate-mapping>
当我删除角色时:
Session.Delete(role);
如果它的角色包含1000个用户,NHibernate会对User表生成1000个删除查询,对UsersInRoles生成1000个删除查询,而不是1个用户和1个到UsersInRoles。
答案 0 :(得分:1)
为什么不直接在数据库中启用Cascade上的Delete?
答案 1 :(得分:1)
最简单的方法是告诉NHibernate不要级联删除并在数据库中启用级联(如果你的数据库支持它)。对于SQL Server,级联选项位于外键的设置下。
这意味着NHibernate将为父记录发出一个delete语句,数据库将在内部级联该操作。