开发者

NHibernate: nullable one-to-one association..?

This is my first time using NHibernate开发者_运维百科, and I'm currently in the process off writing mappings and restructuring the objects in my application so they map more cleanly.

I have a situation which looks a bit like this:

class A
{
    // Properties of A
    //..

    // References an instance of B (but can be null)
    public B BInstance { get; set; }
}

class B
{
    // Properties relevant to a particular instance of A
}

Now, this seems like a one-to-one association to me, but I can find no references in the NHibernate documentation as to whether a nullable one-to-one association is actually possible.

Ideally, the "B Table" in my database would have an "A_ID" column. The presence of a row with that A_ID would indicate that the associated instance of A is in a non-null association. If there is no row with that A_ID, it would indicate a null association.

The only way I can think to map this is to map a collection from A (which the application restricts to 1 or 0 elements), but I'm wondering if there's a more obvious solution that I'm missing.

Thanks in advance for your assistance.

To clarify: I'm using vanilla NHibernate, not Fluent.


You should be able to specify References(x => x.BInstance).Nullable() in your mappings (assuming you are using Fluent nHibernate).


In the end I changed the model so it more closely mapped to the database schema I was trying to achieve.

I did this by making the one-to-one association bi-directional in the object model. (i.e., The B class also held a reference to its associated A class).

This allowed for the straightforward use of a <one-to-one constrained="true" /> association, which is nullable.


Nullable one-to-one mapping is possible using a one-to-one element. See http://ayende.com/Blog/archive/2009/04/19/nhibernate-mapping-ltone-to-onegt.aspx for pretty good summary by Ayende.


in the A mapping you should write:

<many-to-one class="B" name="BInstance" column="a_ID" not-null="false"/>

and in the class put the propert BInstance of type "B". not-null="false" is the default value, I wrote just for enforce that B can be null as you requested.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜