I have a Question table which joins to a Solution table. The solutions are linked to the questions but in order to delete a question, I must delete the solutions for that question first and then delete the question itself.
I have a linq query that retrieves all solutions for a specific question however I’m not sure how to proceed with the deletion of the solutions and then consequently proceed to delete the question.
Here is the code, it recieves overload error messages:
public static void DeleteSol(string qTextInput)
{
ExamineDataContext dc = new ExamineDataContext();
var matchedSol = from q in dc.Questions
where q.QuestionText.Contains(qTextInput)
join s in dc.Solutions
on q.QuestionID equals s.QuestionID
into qs // note grouping
select new
{
solution = qs
};
try
{
dc.Solutions.DeleteOnSubmit(matchedSol);
dc.SubmitChanges();
}
catch (Exception ex)
{
throw ex;
}
}
If you have a foreign key relationship between your questions and solutions, just set it so that deletes are propagated (CASCADE ON DELETE). That way you only have to delete the question and the solutions are automatically deleted by the database.
Using the foreign key relationship will also give you an entity set on your Question entity that will directly load the related Solution entities and make it so you can avoid writing the join logic all the time. You’ll need to delete and re-add your entities after adding the foreign key relationship for the designer to pick it up — or you can add the association by hand in the designer.