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 ;-)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…