Deleting Orphans with Fluent NHibernate

581 views Asked by At

I have been struggling with this issue, couldn't find a solution yet.

I have the following situation (I've cut non-necessary parts):

public class Company : Base // Base has Guid Id
{
    public virtual HeadQuarter  HeadQuarter { get; set; }
}

public class HeadQuarter : Base
{
    public virtual Company      Company     { get; set; }
}

Mappings:

public CompanyMap()
{
    Id(x => x.Id).Column("CompanyId");

    References(x => x.HeadQuarter)
        .Column("HeadQuarterId")
        .Unique()
        .Cascade.All();
}

public HeadQuarterMap()
{
    Id(x => x.Id)
        .Column("HeadQuarterId");

    HasOne(x => x.Company)
            .PropertyRef(x => x.HeadQuarter)
            .Cascade.All();
}

That generates two tables in my DB. I can insert a Company with a HeadQuarter. It works fine.

The problem is that when I remove a Company, the HeadQuarter doesn't get deleted. That's why I use cascading.

How can I achieve that?

1

There are 1 answers

0
Radim Köhler On

I'd say, that the mapping should be inversed. Check the doc

HasOne / one-to-one

In the example below, we are mapping the relationship between a Car entity and a SteeringWheel entity. For our business rules, a Car will only ever have one SteeringWheel so we would map it like so:

public class CarMap : ClassMap<Car>
{
    public CarMap()
    {
        Table( "Vehicles.dbo.Car" );

        Id( x => x.CarId );
        Map( x => x.Name );
        Map( x => x.Year );

        HasOne( x => x.SteeringWheel ).PropertyRef( x => x.Car);
    }
}

public class SteeringWheelMap : ClassMap<SteeringWheel>
{
    public SteeringWheelMap()
    {
        Table( "Vehicles.dbo.SteeringWheel" );

        Id( x => x.SteeringWheelId );
        Map( x => x.Diameter );
        Map( x => x.Color );

        References( x => x.Car, "CarId" ).Unique();
    }
}

So, in our case, we would need the

public CompanyMap()
{
    Id(x => x.Id).Column("CompanyId");


    HasOne(x => x.HeadQuarter)
            .PropertyRef(x => x.Company);
}

public HeadQuarterMap()
{
    Id(x => x.Id)
        .Column("HeadQuarterId");

    References( x => x.Company, "CompanyId" ).Unique();
}