views:

729

answers:

2

Howdy,

I have a mapped entity, Matter, that has a mapped component, Injury.

The only property on the Injury is DateOfInjury which is a nullable datetime.

When I retrieve the Matter, if the DateOfInjury is null, the component is null.

Thus something like this matter.Injury.DateOfInjury will throw.

Could someone explain if I am doing something obvious to cause this behaviour?

I would have expected that the Injury component gets initialized by nHibernate as an object and that the DateOfinjury property is null.

This would be more flexible i would think?

+1  A: 

I think that's the default behavior for a component mapping. The NHibernate docs for component say that if all elements of the component are null, the component itself will just be null.

If you only have a single property in the component, it might make sense to just map it as a nullable DateTime property on the Matter class.

Andy White
Fair enough, the component will ultimately have more properties.I think it would be nice if the component came back not-null, if all properties are optional data, id have to do a null check to cater for nhibernates behavior.
I agree, that behavior is a little strange. I would have expected it to do what you were saying. I guess it makes sense though, it saves Hibernate from creating an extra object when there is nothing to put in it.
Andy White
+3  A: 

I also ran into the same problem of expecting NHibernate to initialize my component even if all its members are null in the DB. My motivation behind this implementation was to move as much logic concerning my component into the component, not having to deal with it being null or not.

Thanks to this post my search for an explanation why my unit tests were failing for all null values inside the component was short. I fixed this piece in the puzzle by extending the auto-property of my component class ArrivalDay and assigning a fresh instance myself when null is assigned:

private ArrivalDay _arrivalDay;
public ArrivalDay ArrivalDay
{
    get { return _arrivalDay; }
    set { _arrivalDay = value ?? new ArrivalDay(); }
}

This works like a charm and means very little overhead on the containing class.

Oliver
Only problem here: This creates troubles for NHibernate when tracking the components. You'll get an 'object references an unsaved transient instance' once you try to flush the instance
Tigraine