knagode
knagode

Reputation: 6135

NHibernate doesnt save object and also no error is showed

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

Upvotes: 0

Views: 2627

Answers (3)

knagode
knagode

Reputation: 6135

I solved my problem using surrogate key.

Upvotes: 0

longday
longday

Reputation: 4170

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

Upvotes: 0

driis
driis

Reputation: 164341

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

Upvotes: 1

Related Questions