Delete linked data in LINQ to EF

I am new to LINQ and EF, and I have a quick question about the forum that I am developing. This forum has topics, and each topic has related answers. I assumed that EF would see a limitation, and when deleting a topic, related answers will also be deleted. Instead, it throws a constraint error. Is there an easy way to delete all related answers without scrolling through them and mark each one for deletion?

For example, in SQL, I would just do something like this:

DELETE FROM topic_replies WHERE TopicID='999' DELETE FROM topics where TopicID='999' 

But in EF, the only way I know this is:

 Topic topic = //LINQ to get topic. foreach (Reply reply in topic.Replies) { dbEntity.Replies.DeleteObject(reply); } dbEntity.Topics.DeleteObject(topic); 

I think itโ€™s great if thatโ€™s what I should do. Just curious if there is a better way. Thanks in advance.

+4
source share
3 answers

In your database, cascade your deletes for these tables ... Then, when you delete the parent, the database will handle the deletion of the child.

Cascading is part of a foreign key

Example

If you are using SQL Server

 ALTER TABLE dbo.PersonAddress ADD CONSTRAINT FK_PersonAddress_Address FOREIGN KEY ( AddressId ) REFERENCES dbo.Address ( AddressId ) ON UPDATE NO ACTION ON DELETE CASCADE -- Here is where you set your Update and Delete Actions for the foreign key constraint. 

Now basically what it says; If I delete a person, then the database will delete all addresses associated with that person.

+4
source

You can customize the cascade when deleted in the owner object in the EF schema.

 <Association Name="FK_ItemChildren_Item"> <End Role="Item" Type="Model.Store.Item" Multiplicity="1"> <OnDelete Action="Cascade" /> </End> <End Role="ItemChildren" Type="Model.Store.ItemChildren" Multiplicity="*" /> <ReferentialConstraint> .. </ReferentialConstraint> </Association> 

Take a look at http://codepolice.net/2008/12/16/cascade-delete-in-entity-framework/

+8
source

Source: https://habr.com/ru/post/1334564/


All Articles