2011-05-10 25 views
1

我對Nhibernate很新,我知道我的問題是不確定如何解決它。NHibernate加入不正確的字段

問題:用戶通過EmployeeID而不是UserID加入員工。這是造成問題,因爲它正在帶回不正確的細節。

Employee.hbm.xml 
<many-to-one name="User" unique="true" column="UserID" /> 

User.hbm.xml 
<one-to-one name="Employee" foreign-key="EmployeeID" class="Employee" lazy="false" /> 

Employee.cs 
public virtual int EmployeeID { get; set; } 
public virtual User User { get; set; } - This is UserID within the actual database 
public virtual string EmailAddress { get; set; } 

User.cs 
public virtual int UserID { get; set; } 
public virtual string Username { get; set; } 
public virtual string Title { get; set; } 
public virtual string Forename { get; set; } 
public virtual string Surname { get; set; } 
public virtual Employee Employee { get; set; } 

以上是別人編碼,我試圖解決它。我試圖改變

<one-to-one name="Employee" foreign-key="UserID" class="Employee" lazy="false" /> 

但是,這仍然會導致問題。

我錯過了什麼嗎?在此先感謝您的幫助:-)

克萊爾

UPDATE

我是通過使一到一個,它會加入對用戶ID希望,但它仍然對加盟EmployeeID。任何人有任何其他想法?再次感謝:-)

Employee.hbm.xml 
<one-to-one name="User" foreign-key="UserID" class="User" lazy="false" /> 

User.hbm.xml 
<one-to-one name="Employee" foreign-key="UserID" class="Employee" lazy="false" /> 
+0

您是否嘗試過使用'很多,TO-一個'而不是'一對一'? – Rippo 2011-05-10 10:26:19

+0

你的外鍵在用戶身份上如何?這不是主要的嗎? – Andrew 2011-06-09 09:58:26

回答

1

你不應該在一個one-to-one映射指定任何列名,因爲這條信息是在關係的另一端的many-to-one映射的一部分。

爲了解決您的問題,您應該刪除從one-to-one映射foreign-key屬性上User實體:

<one-to-one name="Employee" class="Employee" lazy="false" /> 

的NHibernate將使用上Employee實體生成SQL定義的many-to-one映射信息聲明。

<one-to-one name="Employee" class="Employee" constrained="true" lazy="false" /> 

注意,如果一個Employee總是具有關聯一個User(即Employee.User屬性將永遠不會null),那麼你應該通過增加constrained屬性狀態在one-to-one映射這個事實

相關資源:

+0

你好恩里科,我已經刪除了外鍵,但它似乎仍然加入用戶ID - 僱員ID。我已經查看了代碼,它似乎並沒有加入EmployeeID - UserID?還有其他建議嗎? – ClareBear 2011-05-10 10:02:07

0

根據您的實體,用戶和員工之間沒有一對一的關係。請參閱這樣的解釋:

http://jagregory.com/writings/i-think-you-mean-a-many-to-one-sir/

我認爲你需要specifiy您一對一的多到一個代替。

編輯:
我想我可能誤解了您的方案。
您可能需要在此處使用property-ref。所以你映射是這樣的:

<one-to-one name="Employee" class="Employee" property-ref="User" lazy="false" /> 

請查看以下鏈接詳細:Nhibernate Documentation

也有一個類似的職位上所以這裏:one-to-one and specifying column

+0

你好科爾,我確實希望它是一對一的關係。請參閱上面的更新 – ClareBear 2011-06-02 14:27:23

+0

@ClareBear看看我的編輯。 – 2011-06-03 15:08:21

+0

@ClareBear編輯幫助你嗎? – 2011-07-18 12:18:33

0

我會用這裏有多對一的關係,因爲我知道您可能想要合併用戶帳戶,並且一對一可能會導致將員工記錄移至合併用戶時出現問題。

如果你把它看作你的用戶可以有多個員工記錄那麼這可以避免這個問題。

您是否嘗試過類似以下內容:

Employee.hbm.xml

User.hbm.xml

http://ayende.com/blog/3938/nhibernate-mapping-many-to-one