开发者

Does deleting from a LINQ DB also delete records in other tables that have a foreign key association?

开发者 https://www.devze.com 2022-12-15 08:09 出处:网络
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 SubmitC

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 forei开发者_高级运维gn key association and delete them too, or would I need to do like 6 queries?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消