简体   繁体   English

Linq to SQL:删除多对多关系时出错

[英]Linq to SQL: Error deleting many to many relationship

To begin with, lets just start with my error: 首先,让我们从错误开始:

"An attempt was made to remove a relationship between X and Y. However, one of the relationship's foreign keys cannot be set to null" “试图删除X和Y之间的关系。但是,其中一个关系的外键不能设置为null”

Now for the explanation of what I am trying to do... 现在解释我想要做什么......

I have the following database tables: Specimen, Male, Female, SpecimenRelationship. 我有以下数据库表:标本,男性,女性,标本关系。 A male is always a specimen, and a female is always a specimen. 男性总是标本,女性总是标本。 So a specimen has two one-to-many relationship (but logic prevents a specimen have both set). 因此,样本具有两个一对多的关系(但逻辑可以防止样本同时设置)。 Also, a Male can have one-to-many girlfriends, and likewise a Female can have one-to-many boyfriends (hey, this is the 21st century after all). 另外,一个男性可以有一对多的女朋友,同样一个女性可以有一对多的男朋友(嘿,这毕竟是21世纪)。 This has been solved by create a many-to-many table (SpecimenRelationship). 这已通过创建多对多表(SpecimenRelationship)来解决。

The relationships in SQL are setup so that a Specimen delete cascades to both Male and Female. 设置SQL中的关系,以便标本删除级联到Male和Female。 After that the desired function is for deletion of a Male/Female to cascade to SpecimenRelationship - but due to SQL restraints (multiple cycle path rubbish!) this is not done. 之后,所需的功能是删除男性/女性以级联到SpecimenRelationship - 但由于SQL限制(多循环路径垃圾!),这没有完成。 So one cascades and the other is SetNull (lets say the Male is SetNull). 所以一个级联,另一个是SetNull(假设男性是SetNull)。

Now for the bit where is all goes wrong. 现在,这一切都出错了。 When I remove a SpecimenRelationship from the Male entity I get the error above. 当我从Male实体中删除SpecimenRelationship时,我得到上面的错误。 But why does this happen? 但为什么会这样呢? I don't see where I am even deleting the Male entity, am I not understanding how Linq-to-Sql works, why is this not just a straight delete of a SpecimenRelationship entry? 我没有看到我甚至删除了Male实体,我不明白Linq-to-Sql是如何工作的,为什么这不只是直接删除SpecimenRelationship条目?

Here is some example code: 这是一些示例代码:

Male male = GetMaleFromDataContext();

SpecimenRelationship relationshipToRemove = male.SpecimenRelationships.Single(x => x.FemaleID == someFemaleID);

male.SpecimenRelationships.Remove(relationshipToRemove);

DB.SubmitChanges();//error thrown here

Why does the relationship cascade even come into play here? 为什么关系级联在这里发挥作用?

When you create a relationship on a table, your foreign key column's NULL constraint is automatically set to NOT NULL. 在表上创建关系时,外键列的NULL约束将自动设置为NOT NULL。

You need to set it to NULL and your cascade rule will work (I think). 你需要将它设置为NULL,你的级联规则将起作用(我认为)。

The property name in Design mode (Management Studio) is Allow Nulls. 设计模式(Management Studio)中的属性名称为Allow Nulls。

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

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