5

我有一堂课,描述如下:

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

我想将 Contacts 属性映射到下表:

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

我希望它双向映射,即当 Customer1 添加到 Customer2 的联系人时,Customer1 的联系人集合应该包含 Customer2(可能仅在实体重新加载后)。我怎么能那样做?

更新当然我可以映射从左到右和从右到左的集合,然后在运行时组合,但它会......嗯......不好吃......还有其他解决方案吗?无论如何,非常感谢你,FryHard

4

1 回答 1

2

看看这个关于 hibernate 称为单向多对多关联的链接。在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("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; }
}

希望能帮助到你!

于 2008-10-09T07:21:19.947 回答