Can I tell NHibernate not to save certain objects?

498 Views Asked by At

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?

2

There are 2 best solutions below

2
On BEST ANSWER

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.

0
On

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;
        }
    }
}