views:

53

answers:

3

Hi,

I have problem with saving object to database with NHibernate. Program throws no error but record is still not in database. I am also outputting sql queries and the query is not executed.

I use composite key in table "order_product". Table is child of "order".

Database table: order_product

order_id (PK)
product_id (PK)
count
price

Mapping:

<?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# Object:

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; }

}

Save code:

OrderProduct op = new OrderProduct();
op.order_id= 133;
op.product_id = "product_key_id";
op.price = 20.4;
op.count = 10;
OpenSession().Save(op);
A: 

You probably need to either close (Dispose) the Session, or Flush it, to make NHibernate write the changes to the database.

driis
I have tried with wrapping code in transaction and use transaction.Commit();I also tried OpenSession().Flush();But object is still not in database.
knagode
Saving other objects works OK (I tried saving other objects before and after code above).
knagode
OK, then it is probably not a flushing issue.
driis
A: 

Try removing the cascade all on the many-to-one, maybe even remove the fetch.

It doesn't work even if I delete <many-to-one> part of xml file. it seems I am having problem becouse of <composite-id> ...
knagode
A: 

I solved my problem using surrogate key.

knagode