nhibernate之many-to-many的性能

时间:2023-01-02 20:16:36

NHibernate简化了DLL,但降低了性能?

Northwind的Employee和Territories具有多对多的关系,关系存放在EmployeeTerritories表里。

所以在两个Entity建立many-to-many。

Employees.hbm.xml:

  <bag name="EmployeeTerritories" table="EmployeeTerritories" inverse="false" lazy="true" cascade="all-delete-orphan">
   <key>
    <column name="EmployeeID" length="4" sql-type="int" not-null="true"/>
   </key>
   <many-to-many class="DataEntity.Territory, DataEntity"> 
    <column name="TerritoryID" length="20" sql-type="nvarchar" not-null="true"/>
   </many-to-many>
  </bag>   

Territories.hbm.xml: 

    <bag name="TerritoryEmployees" table="EmployeeTerritories" inverse="true" lazy="true" cascade="all-delete-orphan">
      <key>
        <column name="TerritoryID" length="20" sql-type="nvarchar" not-null="true"/>
      </key>
      <many-to-many class="DataEntity.Employee, DataEntity">
        <column name="EmployeeID" length="4" sql-type="int" not-null="true"/>
      </many-to-many>
  </bag>

在EmployeeTerritories里,原先Employee有一个记录对应Territories的5条记录,
EmployeeID  territoryid
15                 01881
15                 01882
15                 01883
15                 01884
15                 01885

现在要给这个EmployeeID=15的记录添加新的Territories记录(territoryid=01886)

            ISession session = SessionFactory.OpenSession(_AssemblyName);

            Employee employee = null;
            Territory territory = null;

            //try...
            //catch...
            //finaly...
            ITransaction transaction = session.BeginTransaction();
            territory = (Territory)session.Get(typeof(Territory), "01886");
            transaction.Commit();

            transaction = session.BeginTransaction();
            employee = (Employee)session.Get(typeof(Employee), 15);
            employee.EmployeeTerritories.Add(territory);
            session.Update(employee);
            transaction.Commit();


用sql查看器查看,发现sql先delete了原来的EmployeeID=15的5条记录,然后再insert这5条记录,再insert新的id=01886的记录,总共执行了7条sql语句

如果原先有上百条记录,那不是要执行几百条记录了?NHibernate中有没有什么配置可以改变?