简体   繁体   English

从LINQ DB中删除是否还会删除其他具有外键关联的表中的记录?

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

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? 客户的外键将进入约6-7个其他表,例如收据,地址,文档等。如果我要使用SubmitChanges()删除客户,是否会使用外键关联来查找所有这些记录并删除它们,还是我需要做6个查询?

This will only happen if you have set up your database tables to do this with cascading deletions (ie on delete cascade ). 仅当您设置数据库表来执行级联删除操作时(例如, on delete cascade ),才会发生这种情况。

For more information please see Insert, Update, and Delete Operations (LINQ to SQL) : 有关更多信息,请参见插入,更新和删除操作(LINQ to SQL)

LINQ to SQL does not support or recognize cascade-delete operations. LINQ to SQL不支持或识别级联删除操作。 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. 如果要删除具有约束的表中的行,则必须在数据库的外键约束中设置ON DELETE CASCADE规则,或使用自己的代码首先删除阻止父级的子对象对象被删除。 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. 默认情况下,大多数数据库系统(包括我认为您使用的SQL Server)将没有任何“ ON DELETE CASCADE”或任何其他操作-因此在这种情况下,将不会发生任何事情。

This T-SQL query will show you your foreign key relationships and whether or not any DELETE or UPDATE referential actions have been defined: 此T-SQL查询将向您显示您的外键关系以及是否已定义任何DELETE或UPDATE引用操作:

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. 如果希望发生某些事情,则需要确保将那些FK关系设置为使用这些级联操作。

See the MSDN docs on Cascading Referential Integrity Constraints for more details. 有关更多详细信息,请参见有关级联引用完整性约束的MSDN文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM