Morning All,
I have a number of entities, Car and Van, each of them having a list of Driver. For example,
public class Car : Entity
{
public virtual string Name { get; set; }
public virtual IList<Driver> Drivers { get; set; }
}
If add the same Driver to a Car and a Van. When I come to delete a Driver off a Car and the Driver exists on a Van then I get a SQL reference exception.
In the database I have a table for Cars, Vans and Drivers, then two joining tables Cars_Drivers
and Vans_Drivers
.
Is there anything I can do in the mapping to make the other objects aware of each other, so delete doesn't throw a reference exception.
EDIT - This is the SQL exception I am getting when I try to delete a Driver from a Car.
NHibernate.Exceptions.GenericADOException: could not delete: [Platform.Core.Driver#2] [SQL: DELETE FROM Drivers WHERE Id = ?] ---> System.Data.SqlClient.SqlException: The DELETE statement conflicted with the REFERENCE constraint "FKCBD4DA8384042473". The conflict occurred in database "Platform", table "dbo.Vans_Drivers", column 'DriverFK'. The statement has been terminated.
EDIT 2 - Mappings and Tables
public class CarMappingOverrides : IAutoMappingOverride<Car>
{
public void Override(AutoMapping<Car> mapping)
{
mapping.HasManyToMany(x => x.Drivers).Cascade.All();
}
}
public class VanMappingOverrides : IAutoMappingOverride<Van>
{
public void Override(AutoMapping<Van> mapping)
{
mapping.HasManyToMany(x => x.Drivers).Cascade.All();
}
}
Cars
- Id
- Name
Cars_Drivers
- Id
- CarFK
- DriverFK
Drivers
- Id
- More Cols
The same goes for the vans as well.
@Handprint - Code used to remove drivers from cars.
Driver driver = DriverService.Get(driverId);
Car car = CarService.Get(carId);
car.Drivers.Remove(driver);
CarService.SaveOrUpdate(car);
Thanks in advance.
Rich