Nhibernate 双向映射

Nhibernate 双向映射,nhibernate,fluent-nhibernate,nhibernate-mapping,Nhibernate,Fluent Nhibernate,Nhibernate Mapping,无论如何,如何创建两个类,它们将被双向引用,并且只使用一个FK?这使我对一对一和一对多的情况感兴趣 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 e

无论如何,如何创建两个类,它们将被双向引用,并且只使用一个FK?这使我对一对一和一对多的情况感兴趣

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?"
}
最简单的是

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

问题是,有时值为null,例如,如果我创建新实例,则为null引用异常:对象引用未设置为对象的实例。如果我在值为null时对其进行测试,则会出现stackowerflow问题—它会为第一个实例创建第二个实例,为第二个实例创建第一个实例