2011-07-29 108 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問題 - 循環創建第一個和第一個實例的第二個實例 –