2012-06-07 22 views
0

我目前正在和ASP.NET MVC應用程序中,我有一個User實體類似如下:如何映射和其他數據源的參考實體與NHibernate

public class User 
{ 
    public virtual int Id { get; protected set; } 
    public virtual string Name { get; protected set; } 
    public virtual string Role { get; protected set; } 
    public virtual Location Location { get; protected set; } 
} 

凡位置同樣也很簡單:

public class Location 
{ 
    public virtual string Id { get; protected set; } 
    public virtual string Building { get; protected set; } 
    public virtual string City { get; protected set; } 
    public virtual string Region { get; protected set; } 
} 

我併發症的出現是因爲我想填充從Active Directory User,而不是數據庫。此外,數據庫持久化的幾個類將用戶引用爲屬性。我有一個用於檢索的ADUserRepository,但我不知道如何將這些用戶集成到我的對象圖中,其餘部分由NHibernate管理。

有沒有一種方法讓NHibernate只保留一個User的ID而不將它作爲Users表的外鍵?我可以將它映射爲一個組件來完成此操作嗎?我也看過實施IUserType進行翻譯。這樣它就會映射到一個簡單的字段,並且可以將ADUserRepository放入鏈中以解析存儲的Id。或者我試圖破解那些不可行的東西?這是我第一次使用NHibernate,因此我非常感謝您能夠提供的任何見解或解決方案。謝謝。

更新

它顯示在此我的最好的解決方案將是映射有IUserType用戶和注射(最好用StructureMap)服務爲其返回之前填充對象。在這個框架下,這裏有幾個問題涉及到主要建議需要定製ByteCodeProvider的主題。我仍然需要這樣做,以便讓IUserType採用參數化構造函數或者在這裏做註釋:NHibernate.ByteCode.LinFu.dll For NHibernate 3.2有所作爲?

+0

如果用戶實體具有與信息的對應表是從某些屬性(即未映射),這絕對能夠活動目錄經由NHibernate的事件偵聽器框架水合{ Ns:NHibernate.Event}或IInterceptor {Ns:NHibernate}。 – kalki

+0

截至目前,用戶沒有自己的表格。我用這種方法做了實驗,實現了一個PostLoadEventListener,但它需要每個引用用戶的對象的邏輯。我寧願隱藏用戶從這些實體返回的方式。 – user1325699

+0

您不需要提供您使用界面來識別用戶作爲成員的實體。 IUserType絕對是一個選項,我對它的疑惑總是需要在hbm中明確的說明(不熟悉流利,所以不知道這一點),我想每個人都知道他的毒藥! – kalki

回答

0

使用用戶類型對用戶轉換爲ID和背面

public class SomeClass 
{ 
    public virtual string Id { get; protected set; } 
    public virtual User User { get; protected set; } 
} 

// in FluentMapping (you have to translate if you want to use mapping by code) 

public SomeClassMap() 
{ 
    Map(x => x.User).Column("user_id").CustomType<UserType>(); 
} 

public class UserType : IUserType 
{ 
    void NullSafeSet(...) 
    { 
     NHibernateUtil.Int32.NullSafeSet(cmd, ((User)value).Id, index); 
    } 
    void NullSafeGet(...) 
    { 
     int id = (int)NHibernateUtil.Int32.NullSafeGet(cmd, ((User)value).Id, index); 
     var userrepository = GetItFromSomeWhere(); 
     return userrepository.FindById(id); 
    } 
}