Cascade Saves with Fluent NHibernate AutoMapping

Ryan Montgomery picture Ryan Montgomery · Feb 25, 2009 · Viewed 10.5k times · Source

How do I "turn on" cascading saves using AutoMap Persistence Model with Fluent NHibernate?

As in:

I Save the Person and the Arm should also be saved. Currently I get

"object references an unsaved transient instance - save the transient instance before flushing"

public class Person : DomainEntity
{
  public virtual Arm LeftArm { get; set; }
}

public class Arm : DomainEntity
{
  public virtual int Size { get; set; }
}

I found an article on this topic, but it seems to be outdated.

Answer

Matt Florence picture Matt Florence · Mar 19, 2009

This works with the new configuration bits. For more information, see http://fluentnhibernate.wikia.com/wiki/Converting_to_new_style_conventions

//hanging off of AutoPersistenceModel    
.ConventionDiscovery.AddFromAssemblyOf<CascadeAll>()


public class CascadeAll : IHasOneConvention, IHasManyConvention, IReferenceConvention
{
    public bool Accept( IOneToOnePart target )
    {
        return true;
    }

    public void Apply( IOneToOnePart target )
    {
        target.Cascade.All();
    }

    public bool Accept( IOneToManyPart target )
    {
        return true;
    }

    public void Apply( IOneToManyPart target )
    {
        target.Cascade.All();
    }

    public bool Accept( IManyToOnePart target )
    {
        return true;
    }

    public void Apply( IManyToOnePart target )
    {
        target.Cascade.All();
    }
}