开发者

nhibernate many to many association - property returns null set

I have a many to many relationship between A and B. (I know I can consider refactoring etc, but that's another matter). my Code does something like this:

// given aId is the Id of an instance of A, and A has a many to many set of B's
    A a = myActiveSession.Get<A>(aId);
    a.Bs.Add(new B() {Name="dave"});

and I get an exception because a.Bs is NULL. this only happens in the context of a test suite, and when I run the single test I get a set and everything is ok. I expect that since the default is lazy fetch, Bs will be initialized when I access the property getter, but if this fails I expect to get an exception, and not simply null... since this way I have no immediate clue what caused this. any ideas?

PS: this is the mapping:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
namespace="MyNamespace" assembly="MyAssembly">
  <class name="A" table="A" dynamic-update="true">
    <id name="id" type="integer" access="field">
      <column name="ID"/>
      <generator class="native"/>
    </id>
    <property name="name" type="string" access="field"/>
    <set name="Bs" table="A_B">
      <key column="a_id"/>
      <many-to-many column="b_id" class="B" />
    </set>
  </class>
</hibernate-mapping>

UPDATE: I've managed to get this to work when I fixed some code that did session cleanup (see @Darin Dimitrov's suggestion), however, I still don't understand what could have caused this strange behavior (instead of receiving some clear exception). so at the moment this开发者_运维知识库 remains a mystery.


Unit tests could execute in parallel from different threads and for this reason they should be independent. I suspect that in your case the Session object is reused in multiple tests and one another test could messes up with Bs property. Make sure the session is created inside your test and is destroyed afterwards i.e.

using (var session = sessionFactory.OpenSession())
{
    A a = myActiveSession.Get<A>(aId);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜