Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

<map> with <index-many-to-many> won't save in NHibernate

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...