我有一个有以下描述的课程:
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的Contacts时,Customer1的Contacts集合应包含Customer2(可能仅在实体重新加载后)。我怎么能这样做?
更新当然我可以映射从左到右和从右到左的集合,然后在运行时进行组合,但它会......嗯......不讨厌...是有其他解决方案?无论如何,谢谢你非常匹配, FryHard !
答案 0 :(得分:2)
看一下hibernate调用unidirectional 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; }
}
希望它有所帮助!