2011-07-29 110 views
0

有什么办法,如何创建两个类,它将被双向引用,并将只使用一个FK?这让我对One-to-One感兴趣,就像One-to-Many案例一样。双向映射

FE:

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

回答

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

问题是,有时值为空(FE如果我创建新实例) 的NullReferenceException:对象没有设置的一个实例目的。 –

+0

如果我测试它,如果值为null,则存在stackowerflow问题 - 循环创建第一个和第一个实例的第二个实例 –