双向映射

时间:2011-07-29 09:05:29

标签: nhibernate fluent-nhibernate nhibernate-mapping

有什么办法,如何创建两个类,这两个类都将被引用并且只使用一个FK?这让我感兴趣的是One-to-One和One-to-Many案例一样。

f.e。:

Class First: Entity
{
Second second;
}

Class Second: Entity
{
First first;
}

String TwoWayReference()
{
First Fir = new First();
Second Sec = new Second();

Fir.second = Sec; // I need it is equivalent to: Sec.first = Fir;

if (Sec.first == Fir)
    return "Is any way how to do this code works and code return this string?";
else
    return "Or it is impossible?"
}

1 个答案:

答案 0 :(得分:0)

最简单的是

class First : Entity
{
    private Second second;
    public virtual Second Second
    {
        get { return this.second; }
        set {
            if (value != null)
            {
                value.First = this;
                this.second = value;
            }
        }
    }
}

class Second : Entity
{
    private First first;
    public virtual First First
    {
        get { return this.first; }
        set {
            if (value != null && value.Second != this)
            {
                value.Second = this;
                this.first = value;
            }
        }
    }
}