简体   繁体   中英

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"

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). This has been solved by create a many-to-many table (SpecimenRelationship).

The relationships in SQL are setup so that a Specimen delete cascades to both Male and 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. So one cascades and the other is SetNull (lets say the Male is SetNull).

Now for the bit where is all goes wrong. When I remove a SpecimenRelationship from the Male entity I get the error above. 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?

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.

You need to set it to NULL and your cascade rule will work (I think).

The property name in Design mode (Management Studio) is Allow Nulls.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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