views:

223

answers:

2

So at the root of my DB, I have a table "Customer." Customer has foreign keys going to about 6-7 other tables such as Receipts, Addresses, Documents etc. If I were to delete a customer using SubmitChanges(), would that seek out all those records with the foreign key association and delete them too, or would I need to do like 6 queries?

+2  A: 

This will only happen if you have set up your database tables to do this with cascading deletions (i.e. on delete cascade).

For more information please see Insert, Update, and Delete Operations (LINQ to SQL):

LINQ to SQL does not support or recognize cascade-delete operations. If you want to delete a row in a table that has constraints against it, you must either set the ON DELETE CASCADE rule in the foreign-key constraint in the database, or use your own code to first delete the child objects that prevent the parent object from being deleted. Otherwise, an exception is thrown.

Andrew Hare
A: 

What kind of cascade action do you have on those foreign key relations??

By default, most database systems (including SQL Server, which I presume you use) will not have any "ON DELETE CASCADE" or any other action - so in that case, nothing would happen.

This T-SQL query will show you your foreign key relationships and whether or not any DELETE or UPDATE referential actions have been defined:

SELECT
    name 'FK Constraint',
    OBJECT_NAME(parent_object_id) 'Parent table',
    OBJECT_NAME(referenced_object_id) 'Referenced table',
    delete_referential_action ,
    delete_referential_action_desc ,
    update_referential_action ,
    update_referential_action_desc 
FROM 
    sys.foreign_keys

If you want something to happen, you need to make sure those FK relations are set to use those cascading actions.

See the MSDN docs on Cascading Referential Integrity Constraints for more details.

marc_s