views:

210

answers:

1

I have the following mapping:

<?xml version='1.0' encoding='utf-8'?>
<hibernate-mapping
    assembly='Core'
    namespace='Core.Models'
    xmlns='urn:nhibernate-mapping-2.2'>
    <class name='Basket'>
     <id name='Id'
      column='id'>
      <generator class='native'/>
     </id>
     <property name="ExternalId" />
     <map name="Items" table="BasketItems" cascade="save-update">
      <key column="BasketId" />
      <index-many-to-many class="Product" column="ProductId" />
      <element column="Quantity" type="System.Int32" />
     </map>
    </class>
</hibernate-mapping>

This is what the Items collection looks like:

public virtual IDictionary<Product, int> Items { get; private set; }

And I have an Add method like so:

public virtual void Add(Product product, int quantity)
{
    if (Items.ContainsKey(product))
     Items[product] += quantity;
    else
     Items.Add(product, quantity);
}

Then the client code looks a bit like this:

var basket = new Basket();
basket.Add(session.Load<Product>(productId));
session.SaveOrUpdate(basket);

Now, the issue is that this client code does save the Basket to the basket table, but does not save any items to the BasketItems table (I'm using SQL Server 2005). However, this test against an in-memory db passes:

[Test]
public void Can_save_basket_with_products() // Passes!!!
{
    var b = new Basket();
    b.Add(_savedProduct);
    _session.SaveOrUpdate(b);
    _session.Flush();
    _session.Evict(b);

    var fromDb = _session.Load<Basket>(b.Id);
    Assert.AreNotSame(b, fromDb);
    Assert.IsTrue(fromDb.Items.ContainsKey(_savedProduct));
}

Any ideas on why it won't save when I'm against my actual DB? What am I missing?

Note: I translated my entities for this example, I hope it's still understandable even if I left something in portuguese ;-)

A: 

Well, found out that I was missing the Flush in my client code. I'm using Castle Monorail and the NHibernate Facility, so it looks as though NH Facility does not flush upon session closing. At least not in a web scenario. I'm assuming the session IS being closed after each request.

Lucio