我试图在NHibernate中建立一个简单的关联(这是我想从头开始使用它的第一个项目) - 它看起来像一个简单的,人为的书籍示例,但由于某种原因我无法让这种关系双向工作。为什么这个简单的NHibernate一对多关系是双向的?
我有一个叫Contact的类,它可以包含很多地址。
这里是简化Contact类:
public class Contact {
// firstName, lastName, etc, etc omitted
// ixContact is the identity value
public virtual int ixContact { get; set; }
public virtual ICollection<Address> addresses { get; set; }
}
这里是地址:
public class Address {
public virtual int ixAddress { get; set; }
public virtual Contact contact { get; set; }
}
这里是映射文件的相关部分,Contact.hbm.xml:
<id name="ixContact">
<generator class="hilo" />
</id>
<bag name="Addresses" inverse="true" cascade="save-update">
<key column="ixContact" />
<one-to-many class="Address />
</bag>
这里是Address.hbm.xml映射文件的相关部分:
<id name="ixAddress">
<generator class="hilo" />
</id>
<many-to-one name="contact" class="Contact" column="ixContact" />
鉴于设置,我运行下面的代码:
_configuration = new Configuration();
_configuration.Configure();
_configuration.AddAssembly(typeof(Contact).Assembly);
_sessionFactory = _configuration.BuildSessionFactory();
_session = _sessionFactory.OpenSession();
new SchemaExport(_configuration).Execute(false, true, false);
Contact firstContact = new Contact { firstName = "Joey", middleName = "JoeJoe", lastName = "Shabadoo" };
using(ITransaction tx = _session.BeginTransaction()) {
firstContact.Addresses = new List<Address>();
Address firstAddress = new Address { /* address data */ };
firstContact.Addresses.Add(firstAddress);
_session.SaveOrUpdate(firstContact);
tx.Commit();
}
_session.Close();
_session.Dispose();
一旦我运行此代码,联系人插入联系人表就好了,地址也被插入地址表,,除了,地址的ixContact字段为NULL,与联系人的ixContact字段的值无关,正如我所期望的。
如果我明确指定了关系的另一端,并说firstAddress.Contact = firstContact
,它工作正常,但我的印象是,NHibernate照顾了这个automagically?
如果是这样,我做错了什么?或者我每次都必须指定RandomContact.Addresses.Add(foo), foo.Contact = RandomContact
?
因此,数据是好的,但你在内存实体不是? – Vadim 2011-05-04 18:21:08
运行上面的代码示例时,数据库中的地址记录与联系人不存在关联(从Contact-> Address有单向关联,但不是来自Address-> Contact)。我受到了印象(虽然就像我说过的,但我肯定可能会错),只要您在映射文件中指定了反例,NHibernate就会为您处理关联的镜像。 – Whisker 2011-05-04 18:59:22
是的,你需要在内存中设置关系的两边。检查这些问题http://stackoverflow.com/q/1061179/40822 http://stackoverflow.com/qestions/713637/inverse-attribute-in-nhibernate – dotjoe 2011-05-04 20:17:35