0

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

Richard Tasker
  • 244
  • 2
  • 12
  • From your description it sounds like your system is attempting to delete the Driver entity (from drivers table), **NOT** a reference from `Van_Drivers` list. More details of your error might help here. – Germann Arlington Nov 08 '12 at 11:03
  • @GermannArlington yes your right. I want the reference from `Car_Drivers` to be deleted but not the Driver or the other reference. I will update my question to include the SQL error message. – Richard Tasker Nov 08 '12 at 12:20
  • You will have to post your table relationships mapping too, it looks like you related your `Car`/`Van` tables directly to `Driver` table instead of `Van_Drivers` and/or `Car_Drivers` – Germann Arlington Nov 08 '12 at 17:40
  • @Richard Tasker What code are you using to delete the driver from your car? – Handprint Nov 09 '12 at 13:56
  • As @GermannArlington said, you will need to post your mappings. Your mappings are definitely not modelled after the entity relationship you want. – Suhas Nov 11 '12 at 17:59

0 Answers0