views:

33

answers:

2

Hi, I have this scenario:

public class Survey : EntityBase
{
    public virtual string Name { get; set; }
}

public class Response : EntityBase
{
    public virtual string Name { get; set; }
    public virtual Survey Survey { get; set; }
}

public class SurveyMap : ClassMap<Survey>
{
    public SurveyMap()
    {
        this.Id(e => e.Id);
        this.Map(e => e.Name);
    }
}

public class ResponseMap : ClassMap<Response>
{
    public ResponseMap()
    {
        this.Id(e => e.Id);
        this.Map(e => e.Name);
        this.References(e => e.Survey);         
    }
}

I want responses to be deleted automatically when I delete surveys, how to I configure this using Fluent NHibernate.

Thanks!

A: 

Try setting the reference to use the delete-orphan option.

NHibernate Cascades: the different between all, all-delete-orphans and save-update

Rafael Belliard
+1  A: 

You should add a property to your Survey entity :

public class Survey : EntityBase 
{
    public virtual string Name { get; set; } 
    public IList<Response> Responses { get; set; }
}

And map it using cascade :

public class SurveyMap : ClassMap<Survey>
{
    public SurveyMap()
    {
        this.Id(e => e.Id);
        this.Map(e => e.Name);
        this.HasMany( e => e.Responses ).Inverse().Cascade().All();
    }
}
mathieu
I'd add: use on-delete="cascade" on the key (I have no idea how to set it with Fluent). That will make for much faster deletes, as the DB will take care of them.
Diego Mijelshon