无法从nhibernate模型中删除最后一项(级联问题)

时间:2013-07-04 07:28:19

标签: c# hibernate nhibernate

基于此映射:nhibernate criteria for selecting from different tables

如果我想删除最后一个Model.Order,我会收到以下错误消息:

"deleted object would be re-saved by cascade (remove deleted object from associations"

这是我的代码:

Model.Unit unitToDelete = m_MainGUI.Manager.RetrieveEquals<Model.Unit>("ID", unitID)[0];
Model.Order currentOrder = m_MainGUI.Manager.RetrieveEquals<Model.Order>("ID", unitToDelete.OrderRef.ID)[0];

if (currentOrder.Units.Count == 1) // last unit of order
{                    
    // delete references
    unitToDelete.OrderRef = null;
    unitToDelete.EmployeeRef = null;



    currentOrder.Units.Remove(unitToDelete); // remove unit from collection                                                       
    m_MainGUI.Manager.Delete<Model.Unit>(unitToDelete);


    m_MainGUI.Manager.Delete<Model.Order>(currentOrder); <---- ERROR
}
else
{
    currentOrder.Units.Remove(unitToDelete); // remove unit from collection
    m_MainGUI.Manager.Save<Model.Order>(currentOrder); // update order with removed unit
}

我的删除方法

public void Delete<T>(T item)
{
    using (m_HibernateSession.BeginTransaction())
    {
        m_HibernateSession.Delete(item);
        m_HibernateSession.Transaction.Commit();
        m_HibernateSession.Flush();
    }
}

Unit.cs(部分内容)

public virtual Employee EmployeeRef { get; set; }
    public virtual Order OrderRef { get; set; }

    public virtual string Employee
    {
        get
        {
            if (EmployeeRef != null) return EmployeeRef.Name;
            else return "";
        }
    }

    public virtual int PONumber
    {
        get
        {
            return OrderRef.PONumber;
        }
    }

    public virtual int OrderID
    {
        get
        {
            return OrderRef.ID;
        }
    }      

Order.cs(部分内容)

private IList<Unit> m_UnitsList = new List<Unit>(); 

public virtual IList<Unit> Units
    {
        get { return m_UnitsList; }
        set { m_UnitsList = value; }
    }

    public virtual string Distributor
    {
        get
        {
            if (Units.Count != 0) return Units[0].Distributor;
            return "";
        }
    }

    public virtual string Department
    {
        get
        {
            if (Units.Count != 0) return Units[0].Department;
            return "";
        }
    }  

任何提示有什么不对?

THX

1 个答案:

答案 0 :(得分:0)

我敢打赌你引用了Unit from Unit,所以你需要做Unit.Order = null。