2

I am using NHibernate with a NullObject pattern to make my views simpler. I use a solution found here by James Gregory

public Address GetAddressOrDefault()
{
  return Address ?? new NullAddress();
}

And Person has an Address property and so on....

This is working very good until I try to save my Person object for a person without an address. Since I created a new instance of the NullPerson object, NHibernate will try to save it. And gives me this:

ids for this class must be manually assigned before calling save():

Is there any way I can get NHibernate to not try to save my NullObjects? Or is there any other way I should be attacking this?

Community
  • 1
  • 1
Eystein Bye
  • 5,016
  • 2
  • 20
  • 18

2 Answers2

3

This event is fired on Save or SaveOrUpdate. What you could perhaps do is create your own SaveOrUpdate listener, that would then set any NullObjects back to null.

public class MySaveOrUpdateEventListener : ISaveOrUpdateEventListener
{
    public void OnSaveOrUpdate(SaveOrUPdate @event)
    {
        if (@event.entity is Person)
        {
            var person = (Person)@event.entity;
            if (person.Address is NullAddress)
                person.Address = null;
        }
    }
}
Vadim
  • 17,897
  • 4
  • 38
  • 62
1

I know you've probably considered this but simplest solution seems to be to the reverse of

public Address GetAddressOrDefault()
{
  return Address ?? new NullAddress();
}

ie, prior to your save call:

public Address GetAddressOrNull(Address address)
{
  return address is NullAddress ? null : address;
}

Or...You might consider using a dedicated class for your ViewModel if things get more complex and using AutoMapper to do the monkey work.

wal
  • 17,409
  • 8
  • 74
  • 109
  • Thank you for good answers. I am afraid it will be a lot of work to revert before saving or to make dedicated classes for ViewModel. But you might be right, this is probably my only solution. My real code is a bit more complex then the example with just person and address. I have about 50 different objects and properties are collections of there objects. – Eystein Bye Dec 01 '11 at 14:28
  • I've had a look at `IUserType` and this stackoverflow question: http://stackoverflow.com/questions/242022/nhibernate-mapping-to-custom-types and it might help you save the null object but you can't make it do what it 'normally' do if its a real Address. The last resort solution is to modify NHibernate source and add an injector to acheive what you need (or maybe you'll come across another solution whilst browsing the source!) – wal Dec 01 '11 at 14:50