< map>与< index-many-to-many>不会保存在NHibernate中 [英] <map> with <index-many-to-many> won't save in NHibernate

查看:79
本文介绍了< map>与< index-many-to-many>不会保存在NHibernate中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下映射:

<?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>

这是Items集合的样子:

This is what the Items collection looks like:

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

我有一个类似的Add方法:

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

现在,问题在于此客户端代码确实将篮子"保存到篮子"表中,但没有将任何项目保存到篮子项"表中(我正在使用SQL Server 2005).但是,此针对内存中数据库的测试通过:

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

推荐答案

好,发现我的客户端代码中缺少 Flush .我正在使用Castle Monorail和NHibernate设备,因此看起来NH Facility在会话关闭时不会刷新.至少在网络场景中没有.我假设每次请求后会话都将关闭.

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.

这篇关于&lt; map&gt;与&lt; index-many-to-many&gt;不会保存在NHibernate中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆