Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting associated data in LINQ to EF

I am new to LINQ and EF and I have a quick question about a forum I am developing. On this forum there are topics, and each topic has associated replies. I assumed that EF would see the constraint and when deleting the topic would also delete the associated replies. Instead it throws a constraint error. Is there an easy way to delete all associated replies without looping through them and marking each one for deletion?

For instance, 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 to do this is:

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

I guess this is fine if this is what I have to do. Just curious if there is a better way. Thanks in advance.

like image 645
Chev Avatar asked Dec 09 '22 11:12

Chev


2 Answers

You can set up cascade on delete in owner object in 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>

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

like image 100
Jahan Zinedine Avatar answered Feb 06 '23 04:02

Jahan Zinedine


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 the foreign key

Example

If your 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 this says is; If i delete a person then the database will delete all addresses that are related to that person

like image 25
John Hartsock Avatar answered Feb 06 '23 04:02

John Hartsock