当试图在数据库中保存具有多对一关系的父母时,孩子不会使用正确的父亲 ID 进行更新。
我在这里发现了类似的问题,尽管它们对我不起作用:
这是我的“父亲”映射,后跟它的类:
<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping assembly="FrancosPoS" namespace="FrancosPoS.DBMapping" xmlns="urn:nhibernate-mapping-2.2">
<class name="order" table="`order`" lazy="true" >
<id name="idOrder">
<generator class="identity" />
</id>
<property name="price">
<column name="price" sql-type="decimal(8,4)" not-null="true" />
</property>
<property name="cash">
<column name="cash" sql-type="tinyint(1)" not-null="false" />
</property>
<property name="credit">
<column name="credit" sql-type="tinyint(1)" not-null="false" />
</property>
<property name="obs">
<column name="obs" sql-type="varchar(350)" not-null="false" />
</property>
<bag name="orderPsi" table="ordPsi" cascade="all" inverse="true">
<key column="idOrdPastaI"/>
<one-to-many class="ordPsi"/>
</bag>
</class>
</hibernate-mapping>
班级:
namespace FrancosPoS.DBMapping
{
public partial class order
{
public order() { }
public virtual int idOrder { get; set; }
public virtual string price { get; set; }
public virtual System.Nullable<int> cash { get; set; }
public virtual System.Nullable<int> credit { get; set; }
public virtual string obs { get; set; }
public virtual IList<ordPsi> orderPsi { get; set; }
}
}
然后,我可以有尽可能多的 orderPsi 引用相同的订单:
<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping assembly="FrancosPoS" namespace="FrancosPoS.DBMapping" xmlns="urn:nhibernate-mapping-2.2">
<class name="ordPsi" table="ord_psi" lazy="true" >
<id name="idOrdPastaI">
<generator class="identity" />
</id>
<many-to-one insert="false" update="false" lazy="false" name="order" class="order">
<column name="idOrder" sql-type="int(11)" not-null="false" />
</many-to-one>
<property name="obs">
<column name="obs" sql-type="varchar(50)" not-null="false" />
</property>
<property name="price">
<column name="price" sql-type="decimal(8,4)" not-null="true" />
</property>
</class>
</hibernate-mapping>
班级:
public partial class ordPsi
{
public ordPsi() { }
public virtual int idOrdPastaI { get; set; }
public virtual order order { get; set; }
public virtual string obs { get; set; }
public virtual string price { get; set; }
}
最后,为了保存它:
order order = new order();
ordPsi orderPsi = new ordPsi();
order.price = "321";
order.cash = 1;
order.credit = 0;
orderPsi.order = order;
orderPsi.price = "20.00";
order.orderPsi = new List<ordPsi>();
order.orderPsi.Add(orderPsi); //add the child to the father
orderDB.setOrder(order);
使用数据库方法:
public string setOrder(order order)
{
try
{
databaseConnection conn = new databaseConnection();
conn.OpenConnection();
conn.Session.SaveOrUpdate(order);
conn.Commit();
conn.CloseConnection();
return "Success";
}
catch (Exception err)
{
return "Error: " + err;
}
}
一切都编译得很好并保存到数据库中,因为我没有空约束,但是 ordPsi 表没有用 orderID 更新。
我还尝试在提交之前保存这两个对象;离开 inverse="false" 而不设置“orderPsi.order = order”,但没有成功。
如果这有帮助,我最关注这两个教程: