0

我在 NHibernate 中有一个双向关系:

<class name="Child" table="Children">
  <many-to-one name="Parent" column="ParentId" not-null="true" />
</class>

<class name="Parent">
  <set name="Children" lazy="true" table="Children" cascade="all">
    <key column="ParentId" not-null="true" />
    <one-to-many class="Child" />
  </set>
</class>

如何在不设置 inverse="true" 并在 Child 上设置 Parent 属性的情况下保存它?
我不想这样做,因为从 POCO 的角度来看它没有多大意义。

或者,是否可以拦截在 NHibernate 代理集合(儿童)上调用的 Add?
在这种情况下,我将把 Parent 设置逻辑放在这里。

4

1 回答 1

4

Unless you're willing to make the foreign key nullable and accept an insert followed by an update, that's the way bidirectional one-to-many works in NHibernate.

I do have a generic implementation of this pattern that you can use... it's a proof of concept; it can be useful or not, depending on how you look at it, as it kinda breaks the POCO approach, but... well, here it is:

public interface IHaveParent<T>
{
    T Parent { get; set; }
}

public interface IHaveMany<T>
{
    ICollection<T> Children { get; }
}

public static class OneToManyHelper
{
    public static void AddChild<TParent, TChild>(this TParent parent,
                                                 TChild child)
    where TChild : IHaveParent<TParent>
    where TParent : IHaveMany<TChild>
    {
        parent.Children.Add(child);
        child.Parent = parent;
    }
}

With this, you can all AddChild on any parent.

The problem with intercepting Add calls is that you'd always need to instantiate your collections using a special method (which, again, is not POCO).

于 2010-04-02T02:53:53.023 回答