2008-10-09 49 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; } 
} 

希望它能帮助!