我在使用 NHibernate 将对象保存到数据库时遇到问题。程序没有抛出错误,但记录仍然不在数据库中。我也输出sql查询,但查询没有执行。
我在表“order_product”中使用复合键。表是“order”的子级。
数据库表:order_product
order_id (PK)
product_id (PK)
count
price
映射:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" auto-import="true">
<class name="Service.OrderProduct, Service" lazy="true" table="order_product">
<composite-id>
<key-property name="productId" column="product_id" type="string"/>
<key-property name="orderId" column="order_id" />
</composite-id>
<property name="count" type="int" column="count" not-null="true" />
<property name="price" type="double" not-null="true" />
<many-to-one name="Order" column="order_id" fetch="join" cascade="all"/>
</class>
</hibernate-mapping>
C# 对象:
public class OrderProduct
{
virtual public OrderProductPK orderProductPK { get; set; }
virtual public int count { get; set; }
virtual public string productId { get; set; }
virtual public int orderId { get; set; }
virtual public double price { get; set; }
virtual public Order Order { get; set; }
public override bool Equals(Object o)
{
OrderProduct a = o as OrderProduct;
if (a.productId.Equals(this.productId) && a.orderId==this.orderId)
{
return true;
}
return false;
}
public override int GetHashCode()
{
int hashCode = 0;
hashCode = hashCode ^ productId.GetHashCode() ^ orderId.GetHashCode();
return hashCode;
}
}
public class OrderProductPK
{
virtual public string productId { get; set; }
virtual public int orderId { get; set; }
}
保存代码:
OrderProduct op = new OrderProduct();
op.order_id= 133;
op.product_id = "product_key_id";
op.price = 20.4;
op.count = 10;
OpenSession().Save(op);
最佳答案
您可能需要关闭(Dispose) session 或刷新它,以使 NHibernate 将更改写入数据库。
关于c# - NHibernate 不保存对象,也没有显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3590676/