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