2012-01-10 91 views
1

我有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); 

如果它的角色包含ns 1000用戶,NHibernate生成1000到用戶表的刪除查詢和1000到UsersInRoles的刪除查詢,而不是1到用戶和1到UsersInRoles。

回答

1

爲什麼不直接在數據庫中啓用Cascade上的Delete?

1

要做的最簡單的事情是告訴NHibernate不要級聯刪除並啓用數據庫中的級聯(如果數據庫支持它)。對於SQL Server,級聯選項位於外鍵的設置下。

這意味着NHibernate會爲父記錄發出一條刪除語句,數據庫會在內部級聯操作。