I’m trying to use Entity Framework 4.0 to add and remove records with a many-to-many relationship. I’ve scoured the web but am just not finding a meaningful example.
As an example, let’s say I have a Drivers and Vehicles table with a junction table VehicleDrivers.
Drivers
- DriverID
- …
Vehicles
- VehicleID
- …
VehicleDrivers
- DriverID
- VehicleID
My questions are:
- How would I write EF statements to add a new vehicle and related driver?
- How would I write EF statements to delete an existing vehicle and any related drivers?
Thanks for any tips.
Something like this:
For existing driver:
For new driver:
Nothing more to do here because the related entries in the join table with all drivers linked to the deleted vehicle will be deleted as well due to enabled cascading delete in the database.
Edit
If you want to delete the drivers as well (and not only the links) in a many-to-many relationship you need to check first if the driver isn’t linked to another vehicle: