2010-05-06 58 views
0

我需要做一個映射,我有一些疑惑。我有這個類:如何映射它? HasOne x參考

public class DocumentType {  
    public virtual int Id { get; set; }  
    /* othes properties for documenttype */ 
    public virtual DocumentConfiguration Configuration { get; set; } 
    public DocumentType() { } 
} 

public class DocumentConfiguration { 
    public virtual int Id { get; set; } 
    /* some other properties for configuration */ 
    public virtual DocumentType Type { get; set; } 

    public DocumentConfiguration() { } 
} 

爲DocumentType對象只有一個DocumentConfiguration,但它不是一個繼承,這只是一個獨特的一個,以單獨的屬性。

這種情況下我的映射應該如何?我應該使用References還是HasOne?有人可以舉個例子嗎?

當我加載一個DocumentType對象時,我想自動加載屬性Configuration(在documentType中)。

非常感謝你們!

乾杯

+0

http://jagregory.com/writings/i-think-you-mean-a-many-to-one-sir/ – Steves 2010-05-06 19:02:16

回答

0

即使您的域中有一對一的關係模型,您的關係模型也可能是一對多的。我懷疑你在這兩個表上共享相同的PK,更有可能你在DocumentType的DocumentConfiguration上有FK。在這種情況下,您可以將它映射爲這樣,因爲您映射的是您的關係模型。所以在DocumentType上它將是HasOne.Inverse.AllDeleteOrphan ...並且在DocumentConfiguration上它將是「參考」。

現在你的域名應該在你描述它的時候公開它。

public class DocumentConfiguration 
{ 
    public DocumentConfiguration() 
    { 
     _internalDocumentConfigurations = new List<DocumentConfiguration>(1); 
    } 

    private IList<DocumentConfiguration> _internalDocumentConfigurations 
    public virtual DocumentType Type 
    { 
    get 
    { 
     return _internalDocumentConfigurations.FirstOrDefault(); 
    } 
    /**/WARNING - no setter here** 
    } 
    public virtual SetDocumentConfiguration(DocumentConfiguration config) 
    { 
     //add your asserts here 
     Add(config); 
    } 

    private virtual Add (DocumentConfiguration config) 
    { 
    //add your asserts here 
     _internalDocumentConfigurations.Add(config) 
     config.DocumentType = this; 
    } 

    public virtual Remove (DocumentConfiguration config) 
    { 
     _internalDocumentConfigurations.Remove(config) 
     config.DocumentType = null; 
    } 

}

public class DocumentConfiguration { 
    public virtual int Id { get; set; } 
    /* some other properties for configuration */ 
    public virtual DocumentType Type { get; protected internal set; } 
0

如果關係真的是一個對一個...然後使用HasOne :-)

http://nhibernate.info/doc/nhibernate-reference/mapping.html#mapping-declaration-onetoone。它有你需要知道的一切。

+0

啊,但是,如何使用?在我使用什麼映射課程? DocmuentConfiguration或DocumentType?我想做一個bidirecional映射=/ 謝謝你 – 2010-05-06 20:56:34

+0

這兩個類應該有一對一的......我建議你在這種情況下使用主鍵關聯。我會添加一個鏈接。 – 2010-05-07 02:14:52