无法将项添加到iesi.collections.generic.iset

时间:2012-11-27 19:24:33

标签: c# nhibernate many-to-many iesi-collections

尝试将项目添加到iset,但不会发生。

var controlPoint = new ControlPoint {Lon = 53.25253, Lat = 56.23422, Radius = 16};
//controlPoint.ApprovedRoutes = new HashedSet<ApprovedRoute>();
controlPoint.Save();

var route = new ApprovedRoute();
route.ControlPoints = new HashedSet<ControlPoint>();
route.ControlPoints.Add(controlPoint);
route.Name = "sometext";
route.Save();

//controlPoint.ApprovedRoutes.Add(route);
//controlPoint.Save();

类:

public class GeoPoint: Entity<long>
{
    public virtual double Lon { get; set; }
    public virtual double Lat { get; set; }
}

public class ControlPoint: GeoPoint
{
    public virtual double Radius { get; set; }
    public virtual Iesi.Collections.Generic.ISet<ApprovedRoute> ApprovedRoutes { get; set; }
}

public class ApprovedRoute : Entity<long>
{
    public virtual string Name { get; set; }
    public virtual Iesi.Collections.Generic.ISet<ControlPoint> ControlPoints { get; set; }
}

这里的映射:

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Transport" namespace="Transport.Models">
  <class name="GeoPoint" table="GeoPoint">
    <id name="Id">
      <column name="id" not-null="true" />
      <generator class="identity" />
    </id>
    <property name="Lon" />
    <property name="Lat" />

    <joined-subclass name="ControlPoint" table="ControlPoint">
      <key column="Id"/>
      <property name="Radius"/>

      <set name="ApprovedRoutes" table="M_ApprovedRoute_ControlPoint" inverse="true">
        <key column="PointId"></key>
        <many-to-many column="RouteId" class="ApprovedRoute" />
      </set>

    </joined-subclass>  
  </class>
</hibernate-mapping>
再来一次:

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Transport" namespace="Transport.Models">
  <class name="ApprovedRoute" table="ApprovedRoute">
    <id name="Id">
      <column name="id" not-null="true" />
      <generator class="identity" />
    </id>
    <property name="Name" />   
    <set name="ControlPoints" table="M_ApprovedRoute_ControlPoint">
      <key column="RouteId"></key>
      <many-to-many column="PointId" class="ControlPoint" />
    </set>    
  </class>
</hibernate-mapping>

我做错了什么? ControlPoint和ApprovedRoute记录显示在表中,但M_ApprovedRoute_ControlPoint仍为空。

P.S。 .Save()调用Session.SaveOrUpdate(obj)

1 个答案:

答案 0 :(得分:0)

很容易。我只是在一个事务中包装SaveOrUpdate,现在它正常工作!

using (ITransaction tx = Session.BeginTransaction())
        {
            try
            {
                Session.SaveOrUpdate(obj);
                Session.Flush();
                tx.Commit();
            }
            catch (HibernateException)
            {
                tx.Rollback();
                throw;
            }
        }