2008-10-09 91 views
5

我有以下描述的一類:NHibernate的雙向許多-to-many關聯

public class Customer { 
    public ISet<Client> Contacts { get; protected set;} 
} 

我想聯繫人屬性映射到下表:

CREATE TABLE user_contacts (
    user1 uuid NOT NULL, 
    user2 uuid NOT NULL 
) 

我希望它雙向映射,即當客戶1添加到客戶2的聯繫人時,客戶1的聯繫人集合應該包含客戶2(可能僅在實體重新加載之後)。我怎麼能這樣做?

更新當然,我可以從左到右和從右到左設置映射,然後在運行時組合,但它會......嗯......不討厭......是否有其他解決方案?任何方式,非常感謝你匹配,FryHard

回答

2

看看這個關於hibernate調用單向的鏈接many-to-many associations。在Castle ActiveRecord我使用HasAndBelongsToMany鏈接,但我不知道它是如何完全映射到nhibernate。

雖然稍微深入瞭解一下您的問題,但看起來您將從客戶雙向鏈接到user_contacts,這可能會破壞多個鏈接。我會玩一個例子,看看我能想出什麼。

ActiveRecord的HBM的文件導出表示該

<?xml version="1.0" encoding="utf-16"?> 
<hibernate-mapping auto-import="true" default-lazy="false" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:nhibernate-mapping-2.2"> 
    <class name="NHibernateMapping.Customer, NHibernateMapping" table="Customer" schema="dbo"> 
    <id name="Id" access="property" column="Id" type="Int32" unsaved-value="0"> 
     <generator class="identity"> 
     </generator> 
    </id> 
    <property name="LastName" access="property" type="String"> 
     <column name="LastName" not-null="true"/> 
    </property> 
    <bag name="ChildContacts" access="property" table="user_contacts" lazy="false"> 
     <key column="user1" /> 
     <many-to-many class="NHibernateMapping.Customer, NHibernateMapping" column="user2"/> 
    </bag> 
    <bag name="ParentContacts" access="property" table="user_contacts" lazy="false" inverse="true"> 
     <key column="user2" /> 
     <many-to-many class="NHibernateMapping.Customer, NHibernateMapping" column="user1"/> 
    </bag> 
    </class> 
</hibernate-mapping> 

ActiveRecord的例子:

[ActiveRecord("Customer", Schema = "dbo")] 
public class Customer 
{ 
    [PrimaryKey(PrimaryKeyType.Identity, "Id", ColumnType = "Int32")] 
    public virtual int Id { get; set; } 

    [Property("LastName", ColumnType = "String", NotNull = true)] 
    public virtual string LastName { get; set; } 

    [HasAndBelongsToMany(typeof(Customer), Table = "user_contacts", ColumnKey = "user1", ColumnRef = "user2")] 
    public IList<Customer> ChildContacts { get; set; } 

    [HasAndBelongsToMany(typeof(Customer), Table = "user_contacts", ColumnKey = "user2", ColumnRef = "user1", Inverse = true)] 
    public IList<Customer> ParentContacts { get; set; } 
} 

希望它能幫助!