Fluent NHibernate - Cascade delete a child object when no explicit parent->child relationship exists
- by John Price
I've got an application that keeps track of (for the sake of an example) what drinks are available at a given restaurant. My domain model looks like:
class Restaurant {
public IEnumerable<RestaurantDrink> GetRestaurantDrinks() { ... }
//other various properties
}
class RestaurantDrink {
public Restaurant Restaurant { get; set; }
public Drink { get; set; }
public string DrinkVariety { get; set; } //"fountain drink", "bottled", etc.
//other various properties
}
class Drink {
public string Name { get; set; }
public string Manufacturer { get; set; }
//other various properties
}
My db schema is (I hope) about what you'd expect; "RestaurantDrinks" is essentially a mapping table between Restaurants and Drinks with some extra properties (like "DrinkVariety" tacked on).
Using Fluent NHibernate to set up mappings, I've set up a "HasMany" relationship from Restaurants to RestaurantDrinks that causes the latter to be deleted when its parent Restaurant is deleted.
My question is, given that "Drink" does not have any property on it that explicitly references RestaurantDrinks (the relationship only exists in the underlying database), can I set up a mapping that will cause RestaurantDrinks to be deleted if their associated Drink is deleted?
Update: I've been trying to set up the mapping from the "RestaurantDrink" end of things using
References(x => x.Drink)
.Column("DrinkId")
.Cascade.All();
But this doesn't seem to work (I still get an FK violation when deleting a Drink).